2

I have an array like this one:

array = ['john', 'jennifer', 'kristen', 'ted']

I would like to convert it to an array of arrays of k elements.
For example, if k = 2 the result should be:

[['john', 'jennifer'], ['kristen', 'ted']]

Is it possible to do so in one line?

1
  • 1
    This is covered in the documentation for Enumerable. It's a really good habit to read through a language's documentation a couple times to become familiar with what's available. Each time through you'll learn more. Commented Feb 29, 2016 at 21:03

2 Answers 2

18

each_slice might help:

array.each_slice(2).to_a
#=> [["john", "jennifer"], ["kristen", "ted"]]
Sign up to request clarification or add additional context in comments.

1 Comment

@Stefan, thank you - I need to learn to link to the API docs.
3

If you want to create two arrays from one with a predicate (an expression which evaluates to either true or false), I would recommend partition

array.partition{ |name| name[0] == 'j' }
#=> [["john", "jennifer"], ["kristen", "ted"]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.