Ruby:如何找到最小数组元素的索引?

前端之家收集整理的这篇文章主要介绍了Ruby:如何找到最小数组元素的索引?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法重写这个更优雅?我认为这是一个坏代码,应该被重构.
>> a = [2,4,10,1,13]
=> [2,13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3

解决方法

It would be interesting to read about other situations (finding all and only last minimal element).

ary = [1,2,1]

# find all matching elements' indexes
ary.each.with_index.find_all{ |a,i| a == ary.min }.map{ |a,b| b } # => [0,2]
ary.each.with_index.map{ |a,i| (a == ary.min) ? i : nil }.compact # => [0,2]

# find last matching element's index
ary.rindex(ary.min) # => 2

猜你在找的Ruby相关文章