Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something if value is present

I frequently find myself writing Ruby code where I check for the presence of a value and subsequently do something with that value if it is present. E.g.

if some_object.some_attribute.present?
  call_something(some_object.some_attribute)
end

I think it would be cool, if it could be written as

some_object.some_attribute.presence { |val| call_something(val) }
=> the return value of call_something

Anyone know if there's such a feature in Ruby or though activesupport?

I opened a pull request for this feature.

like image 492
Niels B. Avatar asked Sep 02 '15 15:09

Niels B.


Video Answer


1 Answers

You can use a combination of presence and try:

If try is called without arguments it yields the receiver to a given block unless it is nil:

'foo'.presence.try(&:upcase)
#=> "FOO"

' '.presence.try(&:upcase)
#=> nil

nil.presence.try(&:upcase)
#=> nil
like image 181
Stefan Avatar answered Sep 17 '22 19:09

Stefan