我经常发现自己正在编写Ruby代码,在该代码中检查值的存在并随后使用该值执行某些操作(如果存在该值)。例如。如果存在值,请执行某些操作
if some_object.some_attribute.present?
call_something(some_object.some_attribute)
end
,我认为它会很酷,如果可以写成
some_object.some_attribute.presence { |val| call_something(val) }
=> the return value of call_something
任何人都知道,如果有在Ruby或者虽然是的ActiveSupport这样的功能?
我为此功能打开了一个pull request。
如果你只是在寻找一个班轮,你可以使用内联if语句:'call_something(some_object.some_attribute)if some_object.some_attribute.present?' – Sculper
这会调用'some_attribute'两次,这对于冗长和性能的原因是不可取的(如果'some_attribute'调用IO) –
'attr = if some_object。 some_attribute.present? call_something(attr) end'这将只调用属性一次 –