In Ruby, iterators are methods supported by Arrays and Hashes. These two classes are Ruby’s tools for dealing with collections, and iterators return elements within a collection, one-by-one. There are two main methods to return elements out of an array or hash.
Method .each
The .each
method can be called when you want to list your collections one element at a time.
Lets first confirm that we can actually use the .each
method on an array. We can do something like so for confirmation:
We have confirmed that .each
is an available method in this Array object with the first line. We can also generate a complete list of methods available by just appending the .methods
method to the object in question. That is the line starting with [4] pry(main)>
in the illustration above.
Lets see a quick demonstration of how we could use the .each
method in practice:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
color_list = [:red, :blue, :green, :white, :brown, :orange, :black] | |
big_colors = [] | |
color_list.each do |color| | |
if color.size > 4 | |
big_colors << color | |
end | |
end | |
big_colors # => [:green, :white, :brown, :orange, :black] |
Above we assigned an array to the color_list
variable. The array contains seven elements initially, and we iterate over the array using the .each
method to select all of the elements larger than 4 letters and place them inside of a different array called big_colors
.
If we wanted to iterate over the array’s index instead of it’s elements, we could utilize the .each_index
method like so:
The .each_index
does exactly the same thing as the .each
method does, except that instead of listing the elements contained inside the array, it lists the indexes.
Method .collect
The methods .collect
and .map
(which are synonymous) creates a new array containing the values returned to it by the block.
Here is an example:
Using .collect
or .collect!
we can temporarily or permanently modify the elements in our array with statements written inside a code block.
Categories: AirPair, Newbie, Ruby
Tags: airpair.com, newbie, Ruby