可能重复:
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
答案 0 :(得分:6)
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]}