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.
Sum of n numbers using while
print "Enter a positive integer n: "
n = gets.chomp.to_i //gets.chomp.to_i is a common method chain used to take
numeric input from the user.
sum = 0
i = 1
while i <= n
sum += i
i += 1
end
puts "The sum of the first #{n} natural numbers is #{sum}."
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 (/)"
print "Enter your choice (1/2/3/4): "
choice = gets.chomp.to_i
if choice >= 1 && choice <= 4
print "Enter the first number: "
num1 = gets.chomp.to_f
print "Enter the second number: "
num2 = gets.chomp.to_f
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
puts "Result: #{num1} #{operator} #{num2} = #{result}"
else
puts "Invalid choice. Please select a valid operation (1/2/3/4)."
end