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

Learn how to convert every number in an array of numbers to their 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]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.