How to Negate All Numbers in a Ruby Array?

Find out how to flip all numbers in a Ruby array

In Ruby, you can negate all numbers in an array of numbers by applying the unary minus operator (-) on every element of the array using Array#map, for example, like so:

arr = [3, 2, -1, 0, 4, -6, -5]
new_arr = arr.map { | num | -num }

print new_arr #=> [-3, -2, 1, 0, -4, 6, 5]

This would create a new array with all numbers in the array negated (i.e. positive numbers will be flipped to negative and negative numbers will be converted to positive). If you want to mutate the original array instead, then you simply need to use Array#map! instead of Array#map, for example, like so:

arr = [3, 2, -1, 0, 4, -6, -5]
arr.map! { | num | -num }

print arr #=> [-3, -2, 1, 0, -4, 6, 5]

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