Ruby Each and Blocks
each is a method that runs a block once for every item in an array. A block is a chunk of code passed to a method.
Printing each item with a for loop
A for loop can print each name on its own line. The loop names the current item and prints it, one turn at a time.
names = ["Ana", "Bo", "Cy"]
for name in names
puts name
endThe same job with each
each runs the block in curly braces once per name. The name between the | marks is the current item.
names = ["Ana", "Bo", "Cy"]
names.each { |name| puts name }A block over many lines
A block with two jobs uses do and end instead of curly braces. This block prints each number and then its double.
numbers = [2, 3, 4]
numbers.each do |number|
puts number
puts number * 2
endAdding up with a block
The block adds each number to total. After the last item, total holds the sum of the whole array.
total = 0
numbers = [10, 20, 30]
numbers.each { |number| total += number }
puts totalExample
prices = [2, 8, 15]
total = 0
prices.each do |price|
puts price
total += price
end
puts totalKey points
- each visits every item in order, from the first item to the last.
- Curly braces hold a block that fits on one line.
- The words do and end hold a block that spans many lines.
- The name between the two | marks holds the current item.
- A block runs once per item, so an empty array runs its block zero times.
In this example, the prices array holds three prices and total starts at 0. The block runs once per price, prints the price, and adds it to total. The last line prints the finished total of 25.
Note
A block is not run at the place it is written. The method runs it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
How many times does a block run when each is called on an array with four items?