Iterating with Arrays

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.


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"]


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}
=> ["and", "so", "did", "he"]


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"] {|word| puts word.capitalize}
=> [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"] {|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"] {|word| word.capitalize}
=> ["He", "Kept", "It", "Hid"]

=> ["he", "kept", "it", "hid"]! {|word| word.capitalize}
=> ["He", "Kept", "It", "Hid"]

=> ["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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s