使用方法值搜索ruby中的哈希值

时间:2015-07-03 15:07:28

标签: ruby-on-rails ruby ruby-on-rails-4

我在搜索哈希值时遇到问题,我的值是方法。我只是不想运行graph_draw(g, vertex_text=g.vertex_properties["name"], ...) 匹配密钥的方法。

plan_type

目前,如果我将“bar”作为def method(plan_type, plan, user) { foo: plan_is_foo(plan, user), bar: plan_is_bar(plan, user), waa: plan_is_waa(plan, user), har: plan_is_har(user) }[plan_type] end 传入,则每个方法都会运行,我怎样才能只运行plan_type方法?

2 个答案:

答案 0 :(得分:8)

这个变种怎么样?

def method(plan_type, plan, user)
  {
    foo: -> { plan_is_foo(plan, user) },
    bar: -> { plan_is_bar(plan, user) },
    waa: -> { plan_is_waa(plan, user) },
    har: -> { plan_is_har(user) }
  }[plan_type].call
end

使用lambdas或procs是一种让事情变得懒惰的好方法,因为只有当他们收到方法call时才执行它们

因此,您可以使用->(lambda literal)作为轻量级包装器,可能需要大量计算,call只能在需要时使用。

答案 1 :(得分:1)

一个非常简单的解决方案:

<强>代码

def method(plan_type, plan=nil, user)
  m =
  case plan_type
  when "foo" then :plan_is_foo
  when "bar" then :plan_is_bar
  when "waa" then :plan_is_waa
  when "har" then :plan_is_har
  else nil
  end

  raise ArgumentError, "No method #{plan_type}" if m.nil?
  (m==:plan_is_har) ? send(m, user) : send(m, plan, user)
end

您当然可以使用哈希而不是case语句。

示例

def plan_is_foo plan, user
  "foo's idea is to #{plan} #{user}"
end

def plan_is_bar plan, user
  "bar's idea is to #{plan} #{user}"
end

def plan_is_waa plan, user
  "waa's idea is to #{plan} #{user}"
end

def plan_is_har user
  "har is besotted with #{user}"
end

method "foo", "marry", "Jane"
  #=> "foo's idea is to marry Jane"

method "bar", "avoid", "Trixi at all costs"
  #=> "bar's idea is to avoid Trixi at all costs" 

method "waa", "double-cross", "Billy-Bob"
  #=> "waa's idea is to double-cross Billy-Bob"

method "har", "Willamina"
  #=> "har is besotted with Willamina"

method "baz", "Huh?"
  #=> ArgumentError: No method baz