I’m trying to get the top 2 values from this array using inject,
a = [1, 2, 5, 7, 4, 9, 2]
b = a.inject(Array.new(2) {0}) {|r, e|
if e > r[0]
r[1] = r[0]
r[0] = e
end
}
but I keep getting the error 'block in <main>': undefined method '[]' for nil:NilClass (NoMethodError) at the line r[1] = r[0]
How could I change it so that r[0] would represent the largest value from a, and r[1] the second largest? Or is there a better, more ruby-like way altogether?
How about:
If you require the reverse order (and using
last(2)from @mu):As far as
injectgoes it always requires that the so called memo object is returned from the block, so that it will be available in the next loop iteration. So this would fix your code: