Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What evaluates to false in Ruby?

Tags:

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
like image 694
user664833 Avatar asked Apr 14 '14 19:04

user664833


People also ask

Is 0 considered false in Ruby?

No it's not. :) Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.

Is False an object in Ruby?

In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass.

What is a boolean in Ruby?

In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .


2 Answers

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

like image 101
nzifnab Avatar answered Sep 20 '22 13:09

nzifnab


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

like image 34
tessi Avatar answered Sep 21 '22 13:09

tessi