开发者

Is there a Ruby-Way™ to handle this kind of loop?

开发者 https://www.devze.com 2023-02-15 14:44 出处:网络
I am trying print section titles for grouped elements in a flat array. I would only like the section title to appear once per group.

I am trying print section titles for grouped elements in a flat array. I would only like the section title to appear once per group.

The example below works, but it feels pretty inelegant for Ruby. I'm certain there must be a better way to do this ;)

#!/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

Desired output

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

I was hoping there was some kind of Array#current or Array#next 开发者_如何学Cinstance methods, but it looks like Ruby Array objects don't keep an internal iterator.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消