0

Lets say I have this:

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
c = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']

And I want this:

d = [[1, 'a', 'ABC'], [2, 'b', 'DEF'], ...]

How can I accomplish this in Ruby?

I tried with .zip

r = []
r.zip(a, b, c)
puts r

But didn't work.

3 Answers 3

2

You need to do as below :-

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
c = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']

a.zip(b,c) 
# => [[1, "a", "ABC"], [2, "b", "DEF"], [3, "c", "GHI"], [4, "d", "JKL"], [5, "e", "MNO"]]

One thing to remember here - Array#zip returns an array of size, equal to the size of the receiver array object.

# returns an array of size 2, as the same as receiver array size.
[1,2].zip([1,5,7]) # => [[1, 1], [2, 5]]
# below returns empty array, as the receiver array object is also empty.
[].zip([1,2,3,4,5]) # => []

For the same reason as I explained above r.zip(a, b, c) returns [].

Sign up to request clarification or add additional context in comments.

3 Comments

facepalm - OMG, this simple... Thanks! "You can accept an answer in 10 minutes" - I'll do it later...
Worth noting: If what you actually have is an array of arrays — like [a, b, c] — you can use transpose on the outer array to get the same effect.
@Chuck Humm, if arrays are not same size.. then error, which zip silently adds nil.
1
[a,b,c].reduce(:zip).map(&:flatten)

Comments

0
d = [a,b,c].transpose
[[1, "a", "ABC"], [2, "b", "DEF"], [3, "c", "GHI"], [4, "d", "JKL"], [5, "e", "MNO"]] 

Comments

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.