0
我有一個數組@dates
,這是UTC日期,並且按遞增順序。我想翻轉數組的索引,以便日期以降序排列。我熟悉JS和Java,不知道如何在ruby中使用指針/索引計數器。這個問題爲好顛倒數組在Ruby中的索引計數器的順序
@dates = [//dates are in here already]
@reverseDates = []
@dates.each do |d|
@reverseDates << @dates.last
end
@dates = @reverseDates
的是,我認爲這是重複的@dates
最後一個索引,當推不將其移動到另一個陣列。
因此,我通過預先考慮數組來獲得它的工作,但是如何在Ruby中包含索引計數器來完成此操作?
@reverseDates = []
@dates.each do |d|
@reverseDates.unshift(d)
end
@dates = @reverseDates
在第一個例子'@ dates.last'永遠不會改變在'each'因爲'@ dates'從未「每個」的變化。請參閱[Enumerable#each_with_index](http://ruby-doc.org/core-1.9.3/Enumerable.html)瞭解如何使用*索引來迭代*;然而,這不是真正的問題,也不是真正的解決方案。 – 2012-12-24 03:45:58
我建議閱讀從A到Z的'Enumerable'模塊的完整API,這些方法中的每一個都非常強大! – akuhn