【发布时间】:2015-09-02 15:17:51
【问题描述】:
我经常发现自己编写 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? -
这会调用
some_attribute两次,出于冗长和性能的原因,这是不可取的(如果some_attribute调用了IO) -
attr = if some_object.some_attribute.present? call_something(attr) end这只会调用一次属性 -
不必说“更新”。如有必要,我们可以判断您是否修改了问题。相反,只需将您的附加信息添加到问题的正常流程中即可。
-
你也可以写
some_object.some_attribute.present & call_something(some_object.some_attribute)。
标签: ruby-on-rails ruby activesupport