Friday, August 05, 2011

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!

6 comments:

  1. 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...

    ReplyDelete
  2. Anonymous10:28 AM

    Is there an equivalent for zero? ?
    Except for != 0 of course...

    ReplyDelete
  3. Yap, you can do my_integer.zero? instead of my_integer == 0

    or my_integer.nonzero?

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Yes, you are right.

    ReplyDelete