Sohan's Blog

Living the Developer's Life

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!


Yes, you are right.
So far as i know is present? not a Ruby method but a Ruby on Rails method.

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

or my_integer.nonzero?
Is there an equivalent for zero? ?
Except for != 0 of course…
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…