2013-02-25 38 views
0

界限的,如果我打算做這樣的事情防止指數走出與#each_index

array.each_index do |i| 
    if array[i] > array[i + i] 
    #something 
    end 
end 

我該如何改變這種防止索引越界?

+1

忘了小白標籤 – cluv 2013-02-25 04:43:37

+0

與長度比較,例如 – 2013-02-25 04:45:35

+0

外部迭代器被認爲是Ruby的一種不好的做法。儘可能避免它。 – sawa 2013-02-25 05:05:50

回答

3
array.each_cons(2) do |current, nekst| 
    if current > nekst 
    #something 
    end 
end 

,或者如果你需要的指數,則:

array.each_cons(2).with_index do |(current, nekst), i| 
    if current > nekst 
    #something with i 
    end 
end 
+0

這是一個很酷的方法 – cluv 2013-02-25 05:00:33

0
array.each_index do |i| 
    if array[i + 1] and array[i] > array[i + i] 
    #something 
    end 
end