Ruby’s Powerful Tools for Iteration: .each, .map, .select and .find

Kevin Peery
2 min readJul 29, 2018

--

Two of the most common tasks performed in Ruby is iteration through an array, or list, and the capture of values out of a hash by keys, usually for the purpose of working with parsed JSON data from an API. In this short article, I will discuss some of the most powerful enumerable mixins, .each, .map, .select and .find.

.each

Much like a loop, it simply does whatever is specified for each element in the array and returns back the same number of elements. As with a loop, the block is what performs an operation on each element. The return value is the same thing that you called it on. To return a transformed array, you must save the block to a variable and return it after the block. The block is the code between the {}, which replaces the long-hand do…end block.

a = [ "a", "b", "c" ]
a.each {|x| print x, " ** " } (the code between {} is the block)
produces: a ** b ** c **

source: https://ruby-doc.org/

.map (.collect)

It always returns an array of the same number of elements as the array on which you called it. It returns an array full of modified or transformed versions of each element in the original array. The block defines the transformation to be performed and specifies what is to be returned in the result.

Note: .map is the same as .collect

a = [ "a", "b", "c", "d" ]
a.collect { |x| x + "*" } #=> ["a*", "b*", "c*", "d*"]
a.map.with_index{ |x, i| x * i } #=> ["", "b", "cc", "ddd"]
a #=> ["a", "b", "c", "d"]

source: https://ruby-doc.org/

.select

It goes through the entire array and grabs all elements for which the specified statement in the block is true. This operation is used to reduce an array’s elements based on the specified condition within the block, often using the comparison operator (==).

Note: .select is the same as. reject and .find_all

(1..10).find_all { |i|  i % 3 == 0 }   #=> [3, 6, 9]

[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]

source: https://ruby-doc.org/

.find

Find goes through an array and returns a single element for which the condition within the block holds true, often using the comparison operator (==). When the element for which the block holds true is found, it stops looking and returns that element.

Note: .find is the same as .detect

(1..100).detect  => #<Enumerator: 1..100:detect>
(1..100).find => #<Enumerator: 1..100:find>

(1..10).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..10).find { |i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> 35
(1..100).find { |i| i % 5 == 0 and i % 7 == 0 } #=> 35

source: https://ruby-doc.org/

References:

--

--

No responses yet