How to Negate 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]

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.