From: "Jesús Gabriel y Galán" Date: 2010-11-30T01:40:44+09:00 Subject: Re: Help sorting an array On Mon, Nov 29, 2010 at 4:47 PM, Jim Burgess wrote: > Hi, > > I have an array consisting of "Event" objects, and string elements which > contain the names of months. > It looks like this: > [#, #, "MARCH", #, > #, "FEBRUARY", #,"JANUARY"] > > Currently the events precede the months they are ordered to. > > Is there any way to reverse this so that the months precede the > events? > Like this: > ["MARCH", #, #, > "FEBRUARY",#, #, "JANUARY", > #] > > I have been scouring the documentation for ages and have also googled > everything I can think of (e.g. Array#split) to try and find a solution, > but with no luck. > > Can anyone point me in the right direction. > I am grateful for any help. > > -- > Posted via http://www.ruby-forum.com/. > > Borrowing from ActiveSupport's Array#split (I modified it to keep the token on which we split as part of the previous group, and also to remove the last group if it's empty): irb(main):093:0> Event = Struct.new :id => Event irb(main):094:0> a = [Event[1], Event[2], "MARCH", Event[3], Event[4], "FEBRUARY", Event[5], "JANUARY"] => [#, #, "MARCH", #, #, "FEBRUARY", #, "JANUARY"] irb(main):095:0> class Array irb(main):096:1> def split(&block) irb(main):097:2> res = inject([[]]) do |results, element| irb(main):098:3* if block.call(element) irb(main):099:4> results.last << element irb(main):100:4> results << [] irb(main):101:4> else irb(main):102:4* results.last << element irb(main):103:4> end irb(main):104:3> results irb(main):105:3> end irb(main):106:2> res.pop if res.last.empty? irb(main):107:2> res irb(main):108:2> end irb(main):109:1> end => nil irb(main):111:0> a.split {|o| o.kind_of? String}.each {|m| el = m.pop; m.unshift el}.flatten => ["MARCH", #, #, "FEBRUARY", #, #, "JANUARY", #] Jesus.