Ruby has a nice little keyword called unless, that checks the opposite of if. So, you are probably used to a code like this:
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:
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:
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, 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...
ReplyDeleteThanks Ashif!
ReplyDeleteIs there an equivalent for zero? ?
ReplyDeleteExcept for != 0 of course...
Yap, you can do my_integer.zero? instead of my_integer == 0
ReplyDeleteor my_integer.nonzero?
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
ReplyDelete.zero? is indeed a ruby method.
Yes, you are right.
ReplyDelete