0

I have an array that represents the hours of operation for a store and is stored as:

schedule = [ [[mon_open, 9],   [mon_close, 5]], 
             [[tues_open, 11], [tues_close, 7]],
             [[wed_open, 9],   [wed_close, 5]],
             [[thur_open,9],   [thur_close, 5]], 
             [[fri_open, 11],  [fri_close, 7]] ]

In this situation I would like to group the arrays such that in the above example [[mon_open, 9],[mon_close, 5]], [[wed_open, 9],[wed_close, 5]], and [[thur_open,9],[thur_close, 5]] would be grouped together...

and similary [[tues_open, 11],[tues_close, 7]], and [[fri_open, 11],[fri_close, 7]] would be grouped together.

Basically I want to group days of the week with the same opening and closing times. Can this be done simply?

Jeremy Thomas
  • 6,240
  • 9
  • 47
  • 92

1 Answers1

1

The way group by works is you select what you want to use for the keys, so for example something like this should do what you want.

here the block just returns an array of the last elements in each of the two element arrays that you have enumerated (I converted the "mon_open", etc to symbols, you could use strings also.

schedule = [ [[:mon_open, 9],   [:mon_close, 5]], 
             [[:tues_open, 11], [:tues_close, 7]],
             [[:wed_open, 9],   [:wed_close, 5]],
             [[:thur_open,9],   [:thur_close, 5]], 
             [[:fri_open, 11],  [:fri_close, 7]] ]


grouped = schedule.group_by { |i| [i[0].last, i[1].last]}
puts grouped

what you get out is this

{[9, 5]=>[[[:mon_open, 9], [:mon_close, 5]], [[:wed_open, 9], [:wed_close, 5]], [[:thur_open, 9], [:thur_close, 5]]], [11, 7]=>[[[:tues_open, 11], [:tues_close, 7]], [[:fri_open, 11], [:fri_close, 7]]]}
nPn
  • 16,254
  • 9
  • 35
  • 58