Ruby Conditionals and Loops
Control flow with if statements and loops
If-Else Statements
if condition # check condition
# code if true
elsif condition2 # additional check
# code
else # default case
# code
end # end if block
Unless Statement
unless condition # if NOT condition
# code executes when false
end
puts "Text" unless condition # inline unless
Case Statement
case variable # evaluate variable
when 1 # if variable is 1
# code
when 2, 3 # if 2 or 3
# code
else # default case
# code
end
While Loop
while condition # repeat while true
# code
end
until condition # repeat until true
# code
end
For and Each Loops
for i in 0..5 # loop 0 to 5
puts i
end
array.each do |item| # iterate array
puts item
end
5.times { puts "Hello" } # repeat 5 times
Loop Control
break # exit loop
next # skip to next iteration
redo # restart current iteration