一個非常簡單的解決方案:
代碼
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
有很多的方式來實現你似乎想(呼叫根據命名類型或其它邏輯的方法)的影響。如果你要立即調用這個方法,像這樣的哈希可能不是最簡單的方法。但是,如果您想延遲撥打電話,則可能會很有用。 –