Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find second largest number from an array in Ruby

Tags:

ruby

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?

like image 380
rubyist Avatar asked Nov 28 '22 03:11

rubyist


2 Answers

Simple:

array.sort[-2]

And you're done :)

like image 109
Maurício Linhares Avatar answered Dec 19 '22 03:12

Maurício Linhares


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
like image 34
Victor Moroz Avatar answered Dec 19 '22 04:12

Victor Moroz