有没有更好的方法来查找数组中最小元素的位置?

unj*_*nj2 3 ruby arrays max

现在我有

def min(array,starting,ending)
  minimum = starting
  for i in starting+1 ..ending
    if array[i]<array[minimum]
      minimum = i
    end    
  end

return minimum
end
Run Code Online (Sandbox Code Playgroud)

Ruby中有更好的"实现"吗?这个仍然看起来像c-ish.谢谢.

ram*_*ion 6

如果要查找最小元素的索引,可以使用Enumerable#enum_for获取项目索引对的数组,并找到最小值Enumerable#min(也是原始数组的最小值).

% irb
irb> require 'enumerator'
#=> true
irb> array = %w{ the quick brown fox jumped over the lazy dog }
#=> ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
irb> array.enum_for(:each_with_index).min
#=> ["brown", 2]
Run Code Online (Sandbox Code Playgroud)

如果要将其绑定到特定的数组索引:

irb> start = 3
#=> 3
irb> stop = 7
#=> 7
irb> array[start..stop].enum_for(:each_with_index).min
#=> ["fox", 0]
irb> array[start..stop].enum_for(:each_with_index).min.last + start
#=> 3
Run Code Online (Sandbox Code Playgroud)