我在 Ruby 中对某个对象执行动态调度时遇到了一个小问题
我想调用一个方法,但我只能通过多次调用来获取它
IE :dynamic_string = 'my_object.other_object.this_method'
我想打电话this_method
给other_object
我my_object.other_object
这是我的 MCVE:
class A
attr_reader :b
def initialize
@b = B.new
end
end
class B
def this
'i want this dynamically'
end
end
a = A.new
a.b.this # => 'i want this dynamically'
dynamic_string = 'b.this'
a.send(dynamic_string) # => error below
NoMethodError: undefined method 'b.this' for #<A:0x000000025598b0 @b=#<B:0x00000002559888>>
据我了解,发送方法试图b.this
在a
对象上调用 litteral 方法。
我知道要让它发挥作用,我必须连续拨打这些电话:
a.send('b').send('this')
但我不知道如何动态地做到这一点
如何实现连续动态调用?(在这个例子中,我只需要 2 个电话,但如果可能的话,我想要一个更通用的解决方案,它适用于每个电话数量)