Notifications
Clear all
Topic starter 01/08/2025 11:16 pm
Ruby Boolean statements are all about making decisions—your code asks “Is this true?” and acts accordingly. Let’s break it down 🧠💎
✅ What Is a Boolean?
In Ruby, a Boolean is a value that’s either:
true
(an instance ofTrueClass
)false
(an instance ofFalseClass
)
These are used to control logic flow, especially in conditionals.
🔍 Truthy vs Falsy
Ruby treats everything as truthy except:
false
nil
That means even values like 0
, ""
, and []
are considered true
in conditionals.
if "hello"
puts "This is truthy!" # This will run
end
🧪 Boolean Expressions
You can create Boolean values using comparisons:
x = 10
puts x > 5 # true
puts x == 10 # true
puts x < 3 # false
🔗 Logical Operators
Combine Boolean expressions:
a = true
b = false
puts a && b # AND → false
puts a || b # OR → true
puts !a # NOT → false
🧠 Using Booleans in Conditionals
age = 20
if age >= 18
puts "You're an adult."
else
puts "You're a minor."
end
Ruby checks whether the condition evaluates to true
or false
and runs the appropriate block.
❓ Predicate Methods
Ruby has methods that return Boolean values and end in a question mark:
[].empty? # true
"hello".include?("e") # true
nil.nil? # true
You can even define your own:
def ready?
true
end