Ruby 返回动态值的散列
我在RubyDocs中偶然发现了这个片段:Ruby 返回动态值的散列,ruby,hash,Ruby,Hash,我在RubyDocs中偶然发现了这个片段: class Interpreter ... Dispatcher = { "a" => instance_method(:do_a), "d" => instance_method(:do_d), "e" => instance_method(:do_e), "v" => instance_method(:do_v) } ... end 是否有任何方法可以使用变量来定义哈希调度程
class Interpreter
...
Dispatcher = {
"a" => instance_method(:do_a),
"d" => instance_method(:do_d),
"e" => instance_method(:do_e),
"v" => instance_method(:do_v)
}
...
end
是否有任何方法可以使用变量来定义哈希调度程序,以表示键和值,如下所示
"#{var}" => instance_method(:do_#{var})
它会迭代所有与“do_uu”前缀匹配的实例方法,并将其添加到Dispatcher
哈希中。@sawa很抱歉看到您删除了答案。我建议使用方法而不是哈希:类D;def调度程序(m)发送(“到#{m}”)结束;def to_a()将“hi”置于末尾;结束;D.new.dispatcher(“a”)=>“hi”
.hi@CarySwoveland-该问题已被编辑,因此失去了一些上下文。我从下一页中摘录了这段代码:,其中散列的赋值具有以其他方式扩展的优势。是的,我看到了(直接链接是)。顺便说一句,如果您不喜欢对问题所做的编辑,请回滚或重新编辑。很高兴知道。我不认为这个问题会从编辑中失去任何必要的东西,但我认为更广泛的背景可能有助于回应你的建议。次要,但你不需要self
。
Dispatcher = Hash.new do |k, h| h[k] = instance_method "do_#{k}" end
Dispatcher = {}
self.instance_methods.grep(/do_*/).each do |method|
Dispatcher[method.to_s.sub "do_", ""] = instance_method(method)
end
Dispatcher = Hash.new do |k, h| h[k] = instance_method "do_#{k}" end