gpt4 book ai didi

ruby-on-rails - Ruby 仅反向索引但保留值?

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:04 27 4
gpt4 key购买 nike

是否可以按给定的顺序遍历结果集,但只反向打印出索引?示例:

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

关于ruby-on-rails - Ruby 仅反向索引但保留值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21035459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com