Ruby Truthy and Falsy Tutorial

In this section, we will learn what the Truthy and Falsy means and what values are Truthy and what values are Falsy.

What is Truthy and What is Falsy in Ruby?

In Ruby, other than the two boolean values true and false, there are other values that are interpreted as true or false. These values are known as Truthy and Falsy values.

In short, there are two values that are considered as falsy values in Ruby:

  • false
  • nil

The value nil means nothing and it is used in Ruby when we want to create a variable but don’t have a value at the moment to assign to it. So we set the variable to nil to say the variable exists but at this time it does not have a value.

Note: other than the value false and nil, the rest of values in Ruby are interpreted as true.

For example: 0, -1, 1000, “jack”, “”, [] etc. these values and many more are considered as true in Ruby because they are neither `false` nor `nil` and so if we use them in a conditional statement like the `if` statement, then the result of the condition in that statement becomes true and its body will run.

Example: running conditional operation based on truthy and falsy values

puts "Please enter a value "

res = gets.to_i

if res

puts "The value you've entered is: #{res}"

end

Output:

Please enter a value

234

The value you've entered is: 234

How does Truthy and Falsy work in Ruby?

In this example, the condition of the `if` statement is the value of the `res` variable, which is something that users enter to the program. Now because the value we’ve entered into the program for the `res` variable is neither false nor nil, then the result of the condition in the if statement becomes true and its body runs as a result.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies