-1

我在 Ruby 中对某个对象执行动态调度时遇到了一个小问题

我想调用一个方法,但我只能通过多次调用来获取它

IE :dynamic_string = 'my_object.other_object.this_method'

我想打电话this_methodother_objectmy_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.thisa对象上调用 litteral 方法。

我知道要让它发挥作用,我必须连续拨打这些电话:

a.send('b').send('this')但我不知道如何动态地做到这一点

如何实现连续动态调用?(在这个例子中,我只需要 2 个电话,但如果可能的话,我想要一个更通用的解决方案,它适用于每个电话数量)

4

1 回答 1

3

尝试这个:

a = A.new
methods_ary = dynamic_string.split('.')
methods_ary.inject(a) { |r, m| r.send(m) }
于 2018-05-09T10:25:54.690 回答