Forge
Forge

Reputation: 6834

Convert Array to Array of Arrays

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?

Upvotes: 2

Views: 2554

Answers (2)

Bobby Matson
Bobby Matson

Reputation: 1488

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"]]

Upvotes: 3

eugen
eugen

Reputation: 9226

each_slice might help:

array.each_slice(2).to_a
#=> [["john", "jennifer"], ["kristen", "ted"]]

Upvotes: 18

Related Questions