The .map method will take an object and a block and will run the block for each element by outputting each of the values which are returned from the block. This will ensure that the original object will remain unchanged until the map is used.
[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]
The Array and the Range are enumerable types.map with a block returning an Array. map! mutates the original array. In order to know where this is helpful and what is the difference between map! and each, an example has been shown below:
names = ['danil', 'edmund']
# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']
names.each { |name| puts name + ' is a programmer' } # here we just do something with each element
The following output:
Danil is a programmer
Edmund is a programmer