0

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)}

1 Answer 1

4

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

The second option did exactly what I needed... thanks
To my surprise, you could fine-tune this by writing r = /\Acab \d+ > \z/; array.slice_before(r).to_a => [["cab 3 > ", 1, 1, 1], ["cab 2 > ", "cat", 1], ["cab 1 > ", 1]]. This works because r === 1 #=> false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.