Sohan's Blog

Things I'm Learning

Ruby Present? Method

Ruby has a nice little keyword called unless, that checks the opposite of if. So, you are probably used to a code like this:

return customer.first_name unless customer.nil?

If you haven’t used present? before, you can in fact turn the above unless into a more familiar and easy to understand if statement:

return customer.first_name if customer.present?

So, in most cases when you are using unless with a negative condition, you can use present? and if instead. I find it way easier to read.

present? does the opposite of blank?. So, you will get the following:

nil.present? #=> false
[].present? #=> false
"hello".present? => true
["a"].present? #=> true
Hope it helps!

Comments

Sohan
Yes, you are right.
michaelkoper
So far as i know is present? not a Ruby method but a Ruby on Rails method. http://api.rubyonrails.org/classes/Object.html#method-i-present-3F

.zero? is indeed a ruby method.
Sohan
Yap, you can do my_integer.zero? instead of my_integer == 0

or my_integer.nonzero?
Anonymous
Is there an equivalent for zero? ?
Except for != 0 of course…
Sohan
Thanks Ashif!
Ashif Manjur
Yes, I often halt at whether I am doing it wright anytime I use 'unless' in any condition. Its much more easier to read if I use 'if'. Thanks for this short but useful post…