Nie*_* B. 6 ruby ruby-on-rails activesupport
我经常发现自己编写Ruby代码,在那里我检查是否存在值,然后在存在的情况下使用该值执行某些操作.例如
if some_object.some_attribute.present?
call_something(some_object.some_attribute)
end
Run Code Online (Sandbox Code Playgroud)
如果它可以写成,我认为它会很酷
some_object.some_attribute.presence { |val| call_something(val) }
=> the return value of call_something
Run Code Online (Sandbox Code Playgroud)
任何人都知道Ruby中是否有这样的功能或者是否支持activesupport?
我打开了此功能的拉取请求.
Ste*_*fan 12
如果
try在没有参数的情况下调用它,则会将接收器生成给定块,除非它是nil:
'foo'.presence.try(&:upcase)
#=> "FOO"
' '.presence.try(&:upcase)
#=> nil
nil.presence.try(&:upcase)
#=> nil
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2352 次 |
| 最近记录: |