0
0
Rubyprogramming~5 mins

Boolean values (true, false, nil) in Ruby

Choose your learning style9 modes available
Introduction

Boolean values help us decide if something is true or false. nil means nothing or no value.

Checking if a light is on or off in a smart home app.
Deciding if a user is logged in or not on a website.
Testing if a box is empty or has something inside.
Stopping a game when a player loses.
Checking if a variable has a value or is empty.
Syntax
Ruby
true
false
nil

true and false are Boolean values representing yes/no or on/off.

nil means no value or nothing, similar to null in other languages.

Examples
Assigning Boolean values and nil to variables.
Ruby
is_raining = true
is_sunny = false
no_value = nil
Using a Boolean value in a decision to print a message.
Ruby
if is_raining
  puts "Take an umbrella"
else
  puts "No umbrella needed"
end
Checking if a variable is nil (has no value).
Ruby
value = nil
if value.nil?
  puts "No value found"
end
Sample Program

This program decides what to do based on hunger and food availability using Boolean values and nil.

Ruby
is_hungry = true
has_food = false
meal = nil

if is_hungry && has_food
  meal = "Eating now"
elsif is_hungry && !has_food
  meal = "Need to buy food"
else
  meal = "Not hungry"
end

puts meal
puts "Meal variable is nil? #{meal.nil?}"
OutputSuccess
Important Notes

In Ruby, only false and nil are treated as false in conditions; everything else is true.

Use .nil? method to check if a variable is nil.

Summary

true and false represent yes/no or on/off.

nil means no value or nothing.

Use Boolean values to make decisions in your code.