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

时间:2011-03-07 21:09:18

标签: ruby design-patterns loops

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

以下示例有效,但对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对象不会保留内部迭代器。

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

foo = [1,1,1,1,2,2,2,3,3]
j = 0
foo.each  do |i|
  unless j == i
    puts "Section #{i}"
    j = i
  end
  puts i
end