Ruby - Blocks and Array each method

Introduction

The each method of the Array class passes each array element in turn to be processed by the block.

The each method does not create a new array to contain the returned values:

Demo

b5 = ["hello","good day","how do you do"].each{|x| x.capitalize }

This time, b5 is unchanged:

["hello", "good day", "how do you do"]

Method ending with an exclamation mark ! actually alter the original objects rather than yielding new values.

If you wanted to use the each method to capitalize the strings in the original array, you could use the capitalize! method:

b6 = ["hello","good day", "how do you do"].each{|x| x.capitalize! }

So, b6 is now as follows:

["Hello", "Good day", "How do you do"]

Related Topic