有没有Ruby-Way™来处理这种循环?

Tha*_*you 1 ruby loops design-patterns

我正在尝试在平面阵列中为分组元素打印节标题.我只想让章节标题每组出现一次.

下面的例子可行,但对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
Run Code Online (Sandbox Code Playgroud)

期望的输出

Section 1
1
1
1
1
Section 2
2
2
2
Section 3
3
3
Run Code Online (Sandbox Code Playgroud)

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

Jak*_*mpl 8

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