Control Statements
Control Statements
`if` / `else`
`elsif`
`case` / `when`
`unless`
`while` / `until`
`for`
`break` / `next`
`return`
if Statement:
The if statement is used to execute a block of code only if a specified condition
is true.
if condition
# Code to be executed if the condition is true
else
# Code to be executed if the condition is false
end
Example:
age = 18
if age >= 18
puts "You are an adult."
else
puts "You are not yet an adult."
end
unless Statement:
The unless statement is the opposite of if. It executes a block of code if a
specified condition is false.
Syntax:
unless condition
# Code to be executed if the condition is false
else
# Code to be executed if the condition is true
end
Example:
temperature = 25
unless temperature >= 30
puts "It's a cool day."
else
puts "It's a hot day."
end
o/p: It's a cool day.
for-in
numbers = [1, 2, 3, 4, 5]
for number in numbers
puts number
end
Until
count = 5
until count == 0
puts "Countdown: #{count}"
count -= 1
end
puts "Blast off!"
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!
case:
puts "Enter a number:"
number = gets.chomp.to_i
case number
when 1..10
puts "You entered a number between 1 and 10."
when 11..20
puts "You entered a number between 11 and 20."
else
puts "The number is not between 1 and 20."
end
Simple Calc:
puts "Simple Arithmetic Calculator"
puts "Available operations:"
puts "1. Addition (+)"
puts "2. Subtraction (-)"
puts "3. Multiplication (*)"
puts "4. Division (/)"
case choice
when 1
result = num1 + num2
operator = "+"
when 2
result = num1 - num2
operator = "-"
when 3
result = num1 * num2
operator = "*"
when 4
if num2 != 0
result = num1 / num2
operator = "/"
else
puts "Cannot divide by zero."
exit
end
end