一个非常简单的解决方案:
代码
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
有很多的方式来实现你似乎想(呼叫根据命名类型或其它逻辑的方法)的影响。如果你要立即调用这个方法,像这样的哈希可能不是最简单的方法。但是,如果您想延迟拨打电话,则可能会很有用。 –