How to Convert All Numbers in a Ruby Array to Absolute Form?

In Ruby, you can change every number in an array of numbers to its absolute value by calling the Numeric#abs method (or its alias, Numeric#magnitude) on each element using Array#map, for example, like so:

arr = [1234, -5678, 12.34, -56.78]
new_arr = arr.map { |item| item.abs }

print new_arr #=> [1234, 5678, 12.34, 56.78]

You may shorten this by using the &: syntax, for example, like so:

arr = [1234, -5678, 12.34, -56.78]
new_arr = arr.map(&:abs)

print new_arr #=> [1234, 5678, 12.34, 56.78]

Using either of the above would create a new array with all numbers in the array in absolute form. If you want to mutate the original array instead, then you simply need to use Array#map! instead of Array#map. For example:

arr = [1234, -5678, 12.34, -56.78]
arr.map!(&:abs)

print arr #=> [1234, 5678, 12.34, 56.78]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.