Ruby Methods and map

Define a method and transform an array with map.

Ruby
def average(values)
  values.sum / values.size.to_f
end

puts average([82, 91, 76, 95])
puts [1, 2, 3].map { |n| n * n }.inspect
Output
86.0
[1, 4, 9]

Explanation

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.

Explore the dry run
Guided walkthroughReady
1def average(values)
2 values.sum / values.size.to_f
3end
4
5puts average([82, 91, 76, 95])
6puts [1, 2, 3].map { |n| n * n }.inspect

Follow 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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]

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

Further reading