Using The Each (.each) Iterator Method on Different Types of Data Structures in Ruby

Nick Frangione
2 min readApr 7, 2021

The each method in Ruby, is a data structure iterator method, which means that it is a way to access stored collections of data, in order to do something with that data.

The each method in Ruby can be used on multiple types of collections of data (arrays, hashes, ranges), and iterates over each element in the collection in order to perform an action.

Base Syntax:

(collection).each do |currentElement|
code
end

Or ...

(collection).each { |currentElement| code }

We call the .each method on the data structure’s name (or the data structure itself), and we pass the currentElement as an argument, within the double pipes (||), to the code block for execution. This code block is either enclosed by do…end or braces({}).

Using the Each Method w/ Array Example:

An array is a collection of any type of elements. In order to be able to access the values out of a given array, and execute our block on each value, we would call the .each method on the array name, and give our block something to do with each element.

sesame_street = ["Elmo", "Cookie Monster", "Big Bird"]
sesame_street.each do |character|
puts character
end
=> Elmo
=> Cookie Monster
=> Big Bird

Using the Each Method w/ Range Example:

The each method functions the same on ranges as with arrays, which makes sense because a range is an ordered number list, which could also be made using an array.

range = (1..7)
range.each do |element|
puts element
end
=> 1
=> 2
=> 3
=> 4
=> 5
=> 6
=> 7
...range = [1, 2, 3, 4, 5, 6, 7]
range.each do |element|
puts element
end
=> 1
=> 2
=> 3
=> 4
=> 5
=> 6
=> 7

Using the Each Method w/ Hash Example:

A hash is a collection of data that has unique key and value pairs assigned to it. This changes up the syntax of each method a little because our code block needs to take two arguments, key and value, rather than just the element like when we use the method with arrays and ranges. To help understand this, think of each key-value pair as an element of your list of key-value pairs, the hash.

For example… If we have a hash, player1, with keys name, job, and enemy, we could iterate over each key-value pair and log them in console using the .each method:

player1 = {name: "Mario", job: "plumber", enemy: "Bowser"}
player1.each do |key, value|
puts "Key: #{key}, Value: #{value}"
end
=> "Key: name, Value: Mario"
=> "Key: job, Value: plumber"

Links to Resources:

--

--