Loops and .each
Repeat actions without repeating yourself
So far, every line of your code has run exactly once. But what if you want to repeat an action many times, like printing every item in a list? That is exactly what loops are for.
The times loop
The simplest loop in Ruby repeats a block of code a set number of times using .times.
3.times do
puts "Hello!"
endThis prints "Hello!" three times in a row. The word do starts the block of repeated code, and end finishes it.
Looping over an array with .each
The most common loop in Ruby is .each, which runs a block of code once for every item in an array.
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts "I like #{fruit}."
endThis prints "I like apple.", "I like banana.", and "I like cherry." The word between the vertical bars, fruit, is a temporary variable that holds the current item during each pass through the loop. You can name it anything you like.
Looping over a hash
You can loop over a hash too, and Ruby gives you both the key and the value on each pass.
person = { name: "Ava", age: 12 }
person.each do |key, value|
puts "#{key}: #{value}"
endThis prints "name: Ava" and then "age: 12".
The block of code between do and end is one of the most important patterns in Ruby. You will meet blocks properly in a later lesson.
Loops let your programs handle lists of any size, whether they hold three items or three million, without writing the same line of code over and over.
Quick check
Q1 What does fruits.each do |fruit| ... end do?
Q2 In 3.times do ... end, how many times does the block run?
Want to save your progress? It's free.
Create a free account