Ruby Methods and map
Define a method and transform an array with map.
On this page
Ruby basics and arrays.
- Define a method and transform an array with map.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A method starts with def and ends with end. The value of its last expression is returned automatically, so return is optional. Ruby does not infer a float from integer division, so the example calls to_f on the size to keep the fraction.
map calls a block on each element and collects the results into a new array, leaving the original unchanged. inspect shows an array in its source-like form, with brackets and commas.
Code example
def average(values)
values.sum / values.size.to_f
end
puts average([82, 91, 76, 95])
puts [1, 2, 3].map { |n| n * n }.inspect86.0 [1, 4, 9]
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
def average(values) values.sum / values.size.to_fend puts average([82, 91, 76, 95])puts [1, 2, 3].map { |n| n * n }.inspectFollow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Define a method with one parameter. | — | — | |
| 344 divided by 4.0; the last expression is the return value. | return = 86.0 | — | |
| Print the average. | return = 86.0 | 86.0 | |
| Square each element and print the new array. | return = 86.0 | 86.0 [1, 4, 9] |
Behind the scenes
How Ruby processes this code
Ruby parses and executes the script. Blocks run when their methods invoke them.
Cost and common mistakes
Both operations are O(n) time.
- 344 / 4 with both integers would give an integer; at least one side must be a Float for decimals.
- map returns a new array; use map! only if you really want to change the original.
Try it yourself
Predict [1, 2, 3].map { |n| n + 10 }.
Reveal answer and reasoning
It returns [11, 12, 13].