Control Structures Cheat Sheet

NameDescriptionSyntaxExamples
if Used to create a branch in your program: Code is only executed if a condition is true
if condition
  code
end
if user_name.empty?
  puts "Please give us a name!"
end
if/else Two way branch: One piece of code is executed if the condition is true, the other if it is false
if condition
  code
else
  code
end
if user_name.empty?
  puts "Please give us a name!"
else
  puts "Hi, #{user_name}!"
end
if/elsif/else Multi way branch: One piece of code is executed if a condition is true, another if another condition is true, and yet another if both are false
if condition
  code
elsif condition
  code
else
  code
end
if user_name.empty?
  puts "Please give us a name!"
elsif user_name == "Ferdinand"
  puts "Hey, I know you!"
else
  puts "Hi, #{user_name}!"
end
loop Loops indefinitely (important: use break to step out of the loop)
loop do
  code
end
loop do
  user_input = gets.chomp
  if user_input == "exit"
    break
  end
end
each Used to loop over all items in a collection (Array, Hash, ...)
collection.each do |variable|
  code
end
[1, 2, 3].each do |integer|
  puts integer
end