Viktor Danilov - 2 years ago 86

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**