I'm trying to get the top 2 values from this array using inject
,
我试图使用inject从这个数组中获取前2个值,
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?
我怎么能改变它,以便r [0]代表a的最大值,r [1]代表第二大?或者是否有更好的,更像红宝石的方式?
1 个解决方案
#1
9
How about:
怎么样:
a.sort[-2, 2]
=> [7, 9]
If you require the reverse order (and using last(2)
from @mu):
如果你需要相反的顺序(并使用@mu中的last(2)):
a.sort.last(2).reverse
=> [9, 7]
As far as inject
goes 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:
就注入而言,它总是要求从块返回所谓的memo对象,以便它在下一个循环迭代中可用。所以这将修复你的代码:
b = a.inject([0, 0]) { |r, e|
# Added fix from @Chuck
if e > r[0]
r[0], r[1] = e, r[0]
elsif e > r[1]
r[1] = e
end
r # <- add this line
}
#1
9
How about:
怎么样:
a.sort[-2, 2]
=> [7, 9]
If you require the reverse order (and using last(2)
from @mu):
如果你需要相反的顺序(并使用@mu中的last(2)):
a.sort.last(2).reverse
=> [9, 7]
As far as inject
goes 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:
就注入而言,它总是要求从块返回所谓的memo对象,以便它在下一个循环迭代中可用。所以这将修复你的代码:
b = a.inject([0, 0]) { |r, e|
# Added fix from @Chuck
if e > r[0]
r[0], r[1] = e, r[0]
elsif e > r[1]
r[1] = e
end
r # <- add this line
}