Introduction
In Ruby, understanding which values count as true or false helps you control decisions in your code easily.
In Ruby, understanding which values count as true or false helps you control decisions in your code easily.
if value # runs if value is truthy else # runs if value is falsy (nil or false) end
Only nil and false are treated as false in Ruby.
Everything else, including 0, empty strings, and empty arrays, is truthy.
nil is falsy, the else branch runs.if nil puts "This won't print" else puts "nil is falsy" end
false is falsy, so else branch runs.if false puts "This won't print" else puts "false is falsy" end
0 is truthy in Ruby, so this prints.if 0 puts "0 is truthy" end
if "" puts "Empty string is truthy" end
This program checks different values and prints if they are truthy or falsy in Ruby.
values = [nil, false, 0, "", [], true] values.each do |val| if val puts "#{val.inspect} is truthy" else puts "#{val.inspect} is falsy" end end
Remember, only nil and false count as false in Ruby.
This makes Ruby conditions simple and predictable.
Only nil and false are falsy in Ruby.
Everything else, even 0 or empty strings, is truthy.
Use this to write clear and simple condition checks.
false and nil are falsy.0, empty string, and empty array are all truthy in Ruby.x is truthy in Ruby?if x automatically checks if x is truthy (not false or nil).if x == true only matches true, missing other truthy values; if x != nil treats false as truthy (false != nil); if x == nil checks the opposite of truthy.if x for truthy check [OK]value = 0 if value puts "Truthy" else puts "Falsy" end
value is assigned 0. The if value checks if value is truthy.0 is truthy, so the if branch runs.var is falsy. What is wrong?
var = nil if var == false puts "Falsy" else puts "Truthy" end
false and nil are falsy in Ruby.var == false, so it misses nil which is also falsy.arr = [false, nil, 0, "", [], true]Which code correctly returns only truthy values?
select { |v| v } keeps only truthy values because v in condition is true for truthy values.arr.select { |v| v != false } keeps nil (nil != false); arr.reject { |v| v } rejects truthy values; arr.select { |v| v == true } keeps only true, missing other truthy values.Pass the test and this pattern moves unknown