Going through an array and applying a code block is a staple of programming, so I’m particularly interested in today’s post on enumerable methods.
#each
One of the more commonly used methods, this, as you can probably guess, applies a given block through all of the items before returning the Array itself. The return is good to know if you’re using this within any method when you remember that Ruby methods will return the last thing evaluated (in this case, the array itself if we only used #each within the method).
masks = ["she", "had", "blue", "skin"] masks.each {|word| puts word.capitalize} She Had Blue Skin => ["she", "had", "blue", "skin"]
#reverse_each
If you wanted to start at the end of the array for your iterating, then #reverse_each is your tool.
masks = ["and", "so", "did", "he"] masks.reverse_each {|word| puts word.upcase} HE DID SO AND => ["and", "so", "did", "he"]
#map
This works just like #each with an important exception, it returns a new array instead of the one that you gave it. Notice that when given the same block as #each, it returns an array of nil objects instead of the original.
masks = ["he", "kept", "it", "hid"] masks.map {|word| puts word.capitalize} He Kept It Hid => [nil, nil, nil, nil]
If we simply tell it to modify the object itself (instead of a puts statement), we get a shiny new array that is not filled with nil objects.
masks = ["he", "kept", "it", "hid"] masks.map {|word| word.capitalize} => ["He", "Kept", "It", "Hid"]
There is also a destructive version of #map if you wanted to modify the original array.
masks = ["he", "kept", "it", "hid"] masks.map {|word| word.capitalize} => ["He", "Kept", "It", "Hid"] masks => ["he", "kept", "it", "hid"] masks.map! {|word| word.capitalize} => ["He", "Kept", "It", "Hid"] masks => ["He", "Kept", "It", "Hid"]
Today’s lorem ipsum is brought to us by the late Shel Silverstein and his poem, “Masks”
She had blue skin.
And so did he.
He kept it hid
And so did she.
They searched for blue
Their whole life through,
Then passed right by—
And never knew.