Viktor Danilov Viktor Danilov - 2 years ago 86
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 Source

v.abs returns the absolute value of the number:

=> 10

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

v = 10
=> -10
v = -10
=> 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download