I have an array a = [3,6,774,24,56,2,64,56,34]
. I need to find the second largest number in a single iteration using Ruby. How do I achieve it?
Simple:
array.sort[-2]
And you're done :)
sort
is probably overkill here, especially for really large arrays. Don't quite understand "single iteration", one line you mean?
a = [3,6,774,24,56,2,64,56,34]
b = a.shift(2).sort
c =
a.inject(b) do |(m2, m), e|
case
when e > m
[m, e]
when e > m2
[e, m]
else
[m2, m]
end
end
c.first #=> 64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With