如何在Ruby中使用max_by和with_index?

时间:2012-06-25 04:30:17

标签: ruby max ruby-1.9.3

a = %w(albatross dog horse)
a.max_by {|x| x.length }   #=> "albatross"

如何使用max_by.with_index获取最大值的索引(在本例中为0)?

Ruby 1.9.3

2 个答案:

答案 0 :(得分:6)

a.each_with_index.max_by { |x,i| x.length }.last

答案 1 :(得分:2)

找到它:a.each_with_index.max_by {|x, idx| x.length }