ecki
ecki

Reputation: 790

splitting an array of arrays, [0] into one, [1] into another

I have a basic array of arrays [[1,2],[2,4],[3,6]]

I want to split that into two arrays, so that...

a = [1,2,3]
b = [2,4,6]

Upvotes: 3

Views: 807

Answers (3)

DaveMongoose
DaveMongoose

Reputation: 905

One way to do this is with a function like each, and to take advantage of Ruby's automatic array splitting:

ary = [[1,2],[2,4],[3,6]]
a = []
b = []

ary.each{|first,second| a << first; b << second}
# The entry [1,2] is automatically split into first = 1 and second = 2

If you want, you can also write it in a single method call using each_with_object

a,b = ary.each_with_object([[],[]]) do |(first, second), result|
  result[0] << first
  result[1] << second
}

A third option would be to use Array.zip:

a,b = ary[0].zip(*ary[1..-1])

zip combines arrays by pairing up the entries with the same indices (as you want to do here). The * here is the splat operator, which unwraps the array of arrays into a series of arguments.

Upvotes: 1

Tanay Sharma
Tanay Sharma

Reputation: 1164

c = [[1,2],[2,4],[3,6]]

You can use map and insert into two different arrays

a = c.map{|x,y| x}
# => [1, 2, 3]

b = c.map{|x,y| y}
 #=> [2, 4, 6]

Edit As @DaveMongoose comment you can also write this

a = c.map(&:first)
b = c.map(&:last)

Upvotes: 1

ray
ray

Reputation: 5552

You can simply use Array#transpose as below,

arr = [[1,2],[2,4],[3,6]]
# => [[1, 2], [2, 4], [3, 6]] 

a, b = arr.transpose
# => [[1, 2, 3], [2, 4, 6]] 
a
# => [1, 2, 3] 
b
# => [2, 4, 6] 

Upvotes: 12

Related Questions