JoMojo
JoMojo

Reputation: 404

ruby array split at String

I have an array that looks like this...

array=["cab 3 > ", #<...>, #<...>, #<...>, "cab 2 > ", #<...>, #<...>, "cab 1 > ", #<...>]

I'd like to split it at every String to get this...

array=[["cab 3 > ", #<...>, #<...>, #<...>], ["cab 2 > ", #<...>, #<...>], ["cab 1 > ", #<...>]]

I tried... but can't figure it out

array.group_by{|name| p name.split(/""/)} 
array.group_by{|name| p name.split(/\"\"/)} 
array.group_by{|name| p name.split(String)}

Upvotes: 0

Views: 175

Answers (1)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369594

So, you want to create a new slice of the array before every String.

This can be achieved using the Enumerable#slice_before method:

array.slice_before(String)

This will return an Enumerator of the form you desire. If you absolutely need an Array, then you can use the Enumerable#to_a method:

array.slice_before(String).to_a
#=> [["cab 3 > ", 1, 1, 1], ["cab 2 > ", 1, 1], ["cab 1 > ", 1]]

Upvotes: 4

Related Questions