Viktor Danilov - 1 year ago 70

Ruby Question

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]`

Answer Source

`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
```