Enumerables, phenumerables in Ruby

Ruby has a host of enumerables. What’s an enumerable? It’s just a handy method that Ruby provides. But it may be confusing to remember which enumerable to use. Here’s the glossary to meditate on.

Essential

#each
Iterates over each of the objects in an array. Note, each will always go through all the objects no matter what is in the body.

#collect/#map
Like #each, but the return value is an array of the values collected.

#select
Returns an array of all the items for which the conditional is true.

#find
Returns the first item for which the condition is true.

#sort / sort_by
Returns an array containing the items sorted. For the differences see http://bit.ly/2xuxRKa.


Useful

#count
Returns the number of items in an array. If a block is given, it counts the number of elements yielding a true value.

#delete_if
Deletes from the collection any items that return true for a certain condition. For example:

scores = [ 97, 42, 75 ]
scores.delete_if {|score| score < 80 } #=> [97]

#max / min
Returns the object in the array with the maximum / minimum value.

#none?
The method returns true if the block never returns true for all elements.

#uniq
Removes duplicate values in the array.

For more information on Ruby’s enumerables check out https://ruby-doc.org/core-2.4.2/Enumerable.html and https://ruby-doc.org/core-2.2.0/Array.html.


Bonus

Advanced programmers save space by using an &: in their enumerable notation. This is the evolution:

arr = [[3, 9, 6], [8, 5, 6], [4, 8, 2]]

Stage I

arr.map do |i|
i.reverse
end

Stage II

array.each {|i| i.reverse}

Stage III

arr.map(&:reverse)

Result

=> [[6, 9, 3], [6, 5, 8], [2, 8, 4]]

Magnifique!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.