Jay*_*Jay 5 ruby ruby-on-rails ruby-on-rails-4
我在搜索哈希值时遇到问题,我的值是方法.我只是不想运行plan_type匹配键的方法.
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
Run Code Online (Sandbox Code Playgroud)
目前如果我传入"bar"作为plan_type,每个方法都将运行,我怎么才能只运行该plan_is_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].call
end
Run Code Online (Sandbox Code Playgroud)
使用lambdas或procs是一种让事情变得懒惰的好方法,因为它们只在接收方法时执行 call
因此,您可以使用->(lambda literal)作为轻量级包装器,可能需要进行繁重的计算call.
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |