gpt4 book ai didi

ruby - 是否有 Ruby-Way™ 来处理这种循环?

转载 作者:太空宇宙 更新时间:2023-11-03 17:08:45 24 4
gpt4 key购买 nike

我正在尝试为平面数组中的分组元素打印部分标题。我只希望章节标题在每个组中出现一次

下面的例子是可行的,但对于 Ruby 来说感觉很不优雅。我确信一定有更好的方法来做到这一点;)

#!/usr/bin/ruby
foo = [1,1,1,1,2,2,2,3,3]

i = 0;

f = foo[i]
comp = f

while(i < foo.count) do
puts "Section #{f}";

while(f == comp) do
puts f
i += 1
f = foo[i]
end

comp = f
end

期望的输出

Section 1
1
1
1
1
Section 2
2
2
2
Section 3
3
3

我希望有某种 Array#currentArray#next 实例方法,但看起来 Ruby Array 对象没有保留内部迭代器。

最佳答案

foo.group_by{|e| e }.each do |header, group| 
puts "Section #{header}"
puts group.join("\n")
end

关于ruby - 是否有 Ruby-Way™ 来处理这种循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5225276/

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