我有一个散列,其中多个键(比如1-5)指向一个对象(让我们调用a)。键(6-10)指向另一个对象(例如,b)。
在某种程度上,我将"b“合并为"a",现在我必须确保每个人都看到同一个对象(同时将"a”合并为"b“,创建两个内容相同的对象不是一个选项)。
是否有方法引用"b“,只需重定向到"a”(键1-10现在指向对象a),而不手动更新键6-10?
发布于 2017-07-21 00:28:06
除非您有某种包装器,否则不能将一个对象切换到另一个对象。除非性能非常重要,否则最容易使用的包装是代理对象,因为您不需要打开它们:它们的行为透明地与包装的对象完全一样。
class ProxyObject
# thanks to https://alisdair.mcdiarmid.org/invisible-proxies-with-ruby/
instance_methods.each do |m|
undef_method(m) unless m =~ /(^__|^nil\?$|^send$|^object_id$)/
end
attr_accessor :target
def initialize(target)
@target = target
end
def respond_to?(symbol, include_priv=false)
@target.respond_to?(symbol, include_priv)
end
private def method_missing(method, *args, &block)
@target.send(method, *args, &block)
end
end
a = 1
b = 10
a_proxy = ProxyObject.new(a)
b_proxy = ProxyObject.new(b)
a_proxy.class # verify how well they masquerade
# => Integer
hash = 10.times.map { |i| [i + 1, i < 5 ? a_proxy : b_proxy] }.to_h
# => {1=>1, 2=>1, 3=>1, 4=>1, 5=>1, 6=>10, 7=>10, 8=>10, 9=>10, 10=>10}
hash.values.sum() # confirm it behaves exactly like a number
# => 55
b_proxy.target = a_proxy.target # switch reference
hash
# => {1=>1, 2=>1, 3=>1, 4=>1, 5=>1, 6=>1, 7=>1, 8=>1, 9=>1, 10=>1}
hash.values.sum() # confirm the reference is changed
# => 10
发布于 2017-07-20 23:16:51
我想我找到了答案,但我还是要对它进行编码。
它将包含一个数组,而不是具有对象的散列。
数组将最初指向自身,array1将成为实际对象。
这就是设置: hash1-5指向arr1,hash6-10指向arr2,arr1指向自身和arr1。
将arr21合并到arr11之后,我将更新arr2以指向arr1。
最后,在每个关键检索之后,我将运行一些类似于
test = hash[6] while test[0] != test test = test[0] end
https://stackoverflow.com/questions/45226346
复制相似问题