哈希返回动态值

时间:2014-10-06 15:45:38

标签: 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

有没有办法使用变量来定义哈希Dispatcher来表示键和值,如下所示?

"#{var}" => instance_method(:do_#{var})

3 个答案:

答案 0 :(得分:2)

Dispatcher = Hash.new do |k, h| h[k] = instance_method "do_#{k}" end

答案 1 :(得分:0)

%w[d a v e].each_with_object({}) do |a, o|
  o[a] = instance_method("do_#{a}")
end

答案 2 :(得分:0)

Dispatcher = {}
self.instance_methods.grep(/do_*/).each do |method|
    Dispatcher[method.to_s.sub "do_", ""] = instance_method(method)
end

迭代所有匹配" do _"的实例方法。前缀并将其添加到Dispatcher哈希。