In Ruby, only the following two values are considered falsy (i.e. objects that evaluate to false
in a boolean context):
false
;nil
.
For example, when you use either of these in a conditional statement, they're evaluated to boolean false
:
if nil
puts "not printed"
else
puts "printed"
end
#=> "printed"
if false
puts "not printed"
else
puts "printed"
end
#=> "printed"
Other than these two values, everything else in Ruby is considered a truthy value, including an empty array, empty string, 0
, etc.:
if []
puts "is truthy"
end
#=> "is truthy"
if ""
puts "is truthy"
end
#=> "is truthy"
if 0
puts "is truthy"
end
#=> "is truthy"
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.