gpt4 book ai didi

ruby 元编程从实例方法获取实例变量的容器类

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:08 25 4
gpt4 key购买 nike

假设我们有三个类:

class SomeClass

def container_class
# ...
end

end

class Container
attr_accessor :property
end

class Container2
attr_accessor :lalala
end

# now I create instances
p = SomeClass.new

c = Container.new
c.property = p
c.property.container_class # => should return Container

c2 = Container2.new
c2.lalala = p
c2.lalala.container_class # => should return Container2

问题:我如何使用 ruby​​ 元编程编写方法 container_class 以便它从调用此方法的地方返回实例的容器(组合)类?

您只能使用元编程。不应手动更改容器类。

最佳答案

我从 here 得到了这个答案.这是获取调用者绑定(bind)的方法:

require 'continuation'

def caller_binding
cc = nil # must be present to work within lambda
count = 0 # counter of returns

set_trace_func lambda { |event, file, lineno, id, binding, klass|
# First return gets to the caller of this method
# (which already know its own binding).
# Second return gets to the caller of the caller.
# That's we want!
if count == 2
set_trace_func nil
# Will return the binding to the callcc below.
cc.call binding
elsif event == "return"
count += 1
end
}
# First time it'll set the cc and return nil to the caller.
# So it's important to the caller to return again
# if it gets nil, then we get the second return.
# Second time it'll return the binding.
return callcc { |cont| cc = cont }
end

现在,你可以定义你的类 SomeClass 如下:

class SomeClass
def container_class
return unless bnd = caller_binding
bnd.eval "self.class"
end
end

关于ruby 元编程从实例方法获取实例变量的容器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com