Matt Elhotiby
Matt Elhotiby

Reputation: 44066

How can I Group ruby objects based on the next values

Ok so I have this array of objects

pry(main)> @something.objects
=> [#<Object id: 2, position: 1, some_type: "Header", entryable_id: 6>,
=> [#<Object id: 3, position: 2, some_type: "Content", entryable_id: 32>,
=> [#<Object id: 4, position: 3, some_type: "Content", entryable_id: 11>,
=> [#<Object id: 6, position: 4, some_type: "Header", entryable_id: 15>,
=> [#<Object id: 7, position: 5, some_type: "Content", entryable_id: 41>,
=> [#<Object id: 8, position: 6, some_type: "Header", entryable_id: 109>,

What I want is the Headers grouped with the next Content like

[{
  header: #<Object id: 2, position: 1, some_type: "Header", entryable_id: 6, 
  content: [#<Object id: 3, position: 2, some_type: "Content", entryable_id: 32>, #<Object   id: 4, position: 3, some_type: "Content", entryable_id: 11>]}, 
  header: #<Object id: 6, position: 4, some_type: "Header", entryable_id: 15>, 
  content: [#<Object id: 7, position: 5, some_type: "Content", entryable_id: 41>],
  content: #<Object id: 8, position: 6, some_type: "Header", entryable_id: 109>
]

So basically the objects all have a position and I want to group all the Headers with the next "Content" until another header comes along...I was thinking of just looping over the objects and creating an array of hashes but I wanted to know if there is an optimal way of doing with, maybe with the DB or another approach

Upvotes: 0

Views: 73

Answers (1)

Reactormonk
Reactormonk

Reputation: 21700

slice_before is what you are looking for.

@something.slice_before {|e| e.some_type == "Header"}.flat_map { |h, *c| {:header => h, :content => c} }

Upvotes: 7

Related Questions