Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 23 / 68

Transforming an Array (map)

In this lesson you will get comfortable with Ruby's map method so you can build a new array from transformed elements. This is for anyone searching for "Ruby map how to use".

.map { |element| operation } applies the same operation to every element and produces a new array. Think of it as a machine on a conveyor belt that processes every product that passes through it in the same way.

The sample code builds a new array with every element doubled using nums.map { |n| n * 2 }. The part in { } is a block - the same thing as the do ... end you met with each, in a short one-line form.

A common stumbling block for beginners is choosing between { } and do ... end. They are the same block, but convention uses { } for short one-line work and do ... end for anything spanning several lines.

collect is an alias that does exactly the same thing. Compared with writing a for loop element by element, what you are trying to do shows up directly in the code - a technique you will meet constantly in practice.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)