What evaluates to false in Ruby?
false
and nil
evaluate to false in Ruby
. Anything else? Please provide links to official/authoritative references.
2.0.0p247 :001 > if true ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE
2.0.0p247 :002 > if false ; puts 'TRUE' ; else puts 'FALSE' ; end
FALSE
2.0.0p247 :003 > if nil ; puts 'TRUE' ; else puts 'FALSE' ; end
FALSE
2.0.0p247 :004 > if 0 ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE
2.0.0p247 :005 > if [] ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE
2.0.0p247 :006 > if {} ; puts 'TRUE' ; else puts 'FALSE' ; end
TRUE
2.0.0p247 :007 > if '' ; puts 'TRUE' ; else puts 'FALSE' ; end
(irb):616: warning: string literal in condition
TRUE
Solution 1:
false
and nil
are the only ones:
http://www.ruby-doc.org/core-2.1.1/FalseClass.html
Rails provides present?
which also includes empty strings and empty arrays: http://api.rubyonrails.org/classes/Object.html#method-i-present-3F
Solution 2:
You just found them all
In Ruby, false and nil are “falsy”, while all other values are “truthy”
as Yehuda Katz mentioned in his blog post in 2009