是否有可能按照給定的順序遍歷結果集,但僅反向打印索引?例如: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
是否有可能按照給定的順序遍歷結果集,但僅反向打印索引?例如: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
我不知道你想達到什麼,但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
>> 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
只需從。減去項目長度的指數,和一個額外的 - 1匹配指數:
items.each_with_index { |val, index| puts (items.length - index - 1).to_s + ": " + val }
offset = items.length - 1
items.each_with_index { |value, i| puts "#{offset - i}: #{value}" }
想你指'項= [ 「一」, 「B」, 「C」]'(陣列'[]',不哈希'{}' ) –
是的,抱歉修復了這個問題。 – Hopstream