2014-01-10 79 views
2

是否有可能按照給定的順序遍歷結果集,但僅反向打印索引?例如:Ruby只反轉索引但保留值?

items = ["a", "b", "c"] 

items.each_with_index do |value, index| 
    puts index.to_s + ": " + value 
end 

給出:

0: a 
1: b 
2: c 

有一種方法,使得輸出是扭轉只有索引:

2: a 
1: b 
0: c 
+0

想你指'項= [ 「一」, 「B」, 「C」]'(陣列'[]',不哈希'{}' ) –

+0

是的,抱歉修復了這個問題。 – Hopstream

回答

3

我不知道你想達到什麼,但reverse_each鏈接統計員可能是有用的:

items.reverse_each.each_with_index do |value, index| 
    puts index.to_s + ": " + value 
end 

生產:

0: c 
1: b 
2: a 

添加另一個reverse_each,達到您要求的結果:

items.reverse_each.each_with_index.reverse_each do |value, index| 
    puts index.to_s + ": " + value 
end 

生產:

2: a 
1: b 
0: c 
3

使用Enumerable#zip

>> items = %w{a b c} 
>> (0...items.size).reverse_each.zip(items) do |index, value| 
?> puts "#{index}: #{value}" 
>> end 
2: a 
1: b 
0: c 
+0

謝謝。我想知道是否有更多的紅寶石方式來實現這一點(也許是一個內置函數)。 – Hopstream

+0

@Hopstream,我添加了一個使用'Enumerable#zip'的替代方法。 – falsetru

0

只需從。減去項目長度的指數,和一個額外的 - 1匹配指數:

items.each_with_index { |val, index| puts (items.length - index - 1).to_s + ": " + val } 
0
offset = items.length - 1 
items.each_with_index { |value, i| puts "#{offset - i}: #{value}" }