Viktor Danilov Viktor Danilov - 7 months ago 22
Ruby Question

How does [v.abs, -v] work?

I know that this code will return a number whose absolute value is the smallest:

arr.min_by {|v| [v.abs, -v]}


How does this part
[v.abs, -v]
work? Can somebody provide an interpretation of this code?

Answer

v.abs returns the absolute value of the number:

-10.abs
=> 10

And -v will just give you the number with inverted sign:

v = 10
-v
=> -10
v = -10
-v
=> 10

min_by will compare first the absolute and then the negated values. So it gives you the smaller number in the array don't matter the sign:

[-1, 2, -3].min_by { |v| [v.abs, -v] }
=> -1
[1,2,-3].min_by { |v| [v.abs, -v] }
=> 1