界限的,如果我打算做這樣的事情防止指數走出與#each_index
array.each_index do |i|
if array[i] > array[i + i]
#something
end
end
我該如何改變這種防止索引越界?
界限的,如果我打算做這樣的事情防止指數走出與#each_index
array.each_index do |i|
if array[i] > array[i + i]
#something
end
end
我該如何改變這種防止索引越界?
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
這是一個很酷的方法 – cluv 2013-02-25 05:00:33
array.each_index do |i|
if array[i + 1] and array[i] > array[i + i]
#something
end
end
忘了小白標籤 – cluv 2013-02-25 04:43:37
與長度比較,例如 – 2013-02-25 04:45:35
外部迭代器被認爲是Ruby的一種不好的做法。儘可能避免它。 – sawa 2013-02-25 05:05:50