Falsy Values in Ruby
Greetings, friends! When working with Boolean contexts such as in if
statements and for
loops, you'll need to know what values make the condition fail due to a falsy value. The falsy values in Ruby are the following:
- The
false
boolean value - The
nil
object
Both of these values will cause a boolean condition to fail:
if false
puts '1. You will see me if the condition is truthy.'
else
puts '1. You will see me if the condition is falsy.'
end
if nil
puts '2. You will see me if the condition is truthy.'
else
puts '2. You will see me if the condition is falsy.'
end
=begin OUTPUT:
1. You will see me if the condition is falsy.
2. You will see me if the condition is falsy.
=end
The conditional statement in every if
statement will fail due to the falsy values, causing the else
block to run.
If you are familiar with JavaScript or read my post on falsy values in JavaScript, then you'll quickly realize that JavaScript treats more values as falsy than Ruby. In fact, the value of zero 0
is actually considered truthy in Ruby!
if 0
puts 'You will see me if the condition is truthy.'
else
puts 'You will see me if the condition is falsy.'
end
=begin OUTPUT:
You will see me if the condition is truthy.
=end
Empty strings, empty arrays, and empty hashes are all considered truthy in Ruby:
if ""
puts '1. You will see me if the condition is truthy.'
else
puts '1. You will see me if the condition is falsy.'
end
if []
puts '2. You will see me if the condition is truthy.'
else
puts '2. You will see me if the condition is falsy.'
end
if {}
puts '3. You will see me if the condition is truthy.'
else
puts '3. You will see me if the condition is falsy.'
end
=begin OUTPUT:
1. You will see me if the condition is truthy.
2. You will see me if the condition is truthy.
3. You will see me if the condition is truthy.
=end
Keep all this information in mind when you are developing web applications using Ruby on Rails when switching between Ruby and JavaScript! It's important to know what is considered falsy in Ruby versus what is considered falsy in JavaScript.