gpt4 book ai didi

ruby - 动态方法链?

转载 作者:数据小太阳 更新时间:2023-10-29 07:11:08 24 4
gpt4 key购买 nike

如何在对象上调用方法名称的嵌套哈希?

例如,给定以下哈希:

hash = {:a => {:b => {:c => :d}}}

我想创建一个方法,给定上面的散列,执行以下操作:

object.send(:a).send(:b).send(:c).send(:d)

我的想法是我需要从一个未知的关联中获取一个特定的属性(这个方法不知道,但程序员知道)。

我希望能够指定一个方法链来以嵌套哈希的形式检索该属性。例如:

hash = {:manufacturer => {:addresses => {:first => :postal_code}}}
car.execute_method_hash(hash)
=> 90210

最佳答案

我会使用数组而不是散列,因为散列允许不一致(如果(子)散列中有多个键怎么办?)。

object = Thing.new
object.call_methods [:a, :b, :c, :d]

使用数组,以下工作:

# 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

call_methods 中,我们在符号数组中使用了 inject,这样我们就可以将每个符号发送到方法执行的结果中,该结果由先前的方法 send 返回。上次发送的结果由inject自动返回。

关于ruby - 动态方法链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882062/

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