如何在对象上调用方法名称的嵌套哈希?
例如,给定以下哈希:
hash = {:a => {:b => {:c => :d}}}
Run Code Online (Sandbox Code Playgroud)
我想创建一个方法,给定上面的哈希,相当于以下内容:
object.send(:a).send(:b).send(:c).send(:d)
Run Code Online (Sandbox Code Playgroud)
我的想法是,我需要从未知的关联中获取特定属性(此方法未知,但程序员已知).
我希望能够指定一个方法链来以嵌套哈希的形式检索该属性.例如:
hash = {:manufacturer => {:addresses => {:first => :postal_code}}}
car.execute_method_hash(hash)
=> 90210
Run Code Online (Sandbox Code Playgroud)
tes*_*ssi 11
我使用数组而不是散列,因为散列允许不一致(如果(子)散列中有多个键,会怎样?).
object = Thing.new
object.call_methods [:a, :b, :c, :d]
Run Code Online (Sandbox Code Playgroud)
使用数组,以下工作:
# This is just a dummy class to allow introspection into what's happening
# Every method call returns self and puts the methods name.
class Thing
def method_missing(m, *args, &block)
puts m
self
end
end
# extend Object to introduce the call_methods method
class Object
def call_methods(methods)
methods.inject(self) do |obj, method|
obj.send method
end
end
end
Run Code Online (Sandbox Code Playgroud)
在call_methods我们使用inject的符号阵列中,使我们每一个符号发送到由以前的方法发送返回方法执行的结果.上次发送的结果将自动返回inject.
| 归档时间: |
|
| 查看次数: |
1667 次 |
| 最近记录: |