如何从Ruby中的最后一个元素迭代数组

时间:2011-11-17 04:07:47

标签: ruby arrays

  

可能重复:
  How to iterate through an array starting from the last element? (Ruby)

我试图反过来迭代列表,但我无法弄明白。

这是我的代码:

#!/usr/bin/ruby
presidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]

for ss in -presidents.length...0
    print  ": ", presidents[ss], "\n";
end

3 个答案:

答案 0 :(得分:6)

使用reverse_each

presidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]
presidents.reverse_each { |president| p president }

答案 1 :(得分:0)

presidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]

presidents.reverse.each do |president|
  puts president
end

答案 2 :(得分:0)

这是另一种方式

(presidents.length-1).step(0,-1) {|i| p presidents[i]}