Collection Methods in Ruby

Methods that call a block repeatedly are called iterator methods.

Iterating through Arrays with #each

Suppose we have an array of days of the week, and we want to loop through, capitalize and output each day of the week.

week = [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]

In other languages you might use a conventional for or while loop to step through each element of the array performing your given action, but with ruby you get a lot of built in iterator methods for collections.

Our ruby code might look something like this:

week.each do |day|
puts day.capitalize
end

Using this #each iterator method is far less prone to error than building a new iterator for every collection you need to iterate through.

Lets look at this in closer detail for the first three iterations of the above code:

Iteration One Outputs:

#=> "Sunday" 

Why?

Well, on iteration one, #each method starts on the first element of the array. The each method passes that element “sunday” to the block and what ever code we have in the block modifies or outputs the object. In this case, we have asked it to output (#puts) the element and #capitalize it.

Iteration Two Outputs:

#=> "Monday"

The same thing is happening here, but now the second iteration grabs the second element of the array passes it to the block and the code we specify in the block modifies the element.

Iteration Three Outputs:

#=> "Tuesday"

Third iterations now grabs the third element and so on, until it reaches the end of the array.

Photo by Sangga Rima Roman Selia on Unsplash

Iterating through Hashes with #each

Suppose we have a hash of states and capitols.

capitols = { “Colorado” => “Denver”, “California” => “Sacramento”, “Minnesota” => “St. Paul” } 

Given the above hash, lets iterate through it:

capitols.each do |key, value|
puts "The State Capitol for: #{key} is #{value}"
end

Above we executed the block code for each key/value pair in the hash which output the following strings:

First Iteration: #=> "The State Capitol for: Colorado is Denver"Second Iteration: #=> "The State Capitol for: California is Sacramento"Third Iteration: #=> "The State Capitol for: Minnesota is St. Paul"

The takeaway here is that #each may work differently depending on the collection. We passed one block parameter with the #each method for the array, and two block parameters for the hash.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store