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


i trying print section titles grouped elements in flat array. section title appear once per group.

the example below works, feels pretty inelegant ruby. i'm there must better way ;)

#!/usr/bin/ruby foo = [1,1,1,1,2,2,2,3,3]  = 0;  f = foo[i] comp = f  while(i < foo.count)   puts "section #{f}";    while(f == comp)     puts f     += 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 hoping there kind of array#current or array#next instance methods, looks ruby array objects don't keep internal iterator.

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

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -