Merging arrays into nested

arr1 = [10,20,30]
arr2 = [100,200,300]
arr3 = [40,50,60]

desired oupput will be like below
result = [[10,100,40],[20,200,50],[30,300,60]]
how can i achieve this?

Exactly as you wrote?

Also:

result = [arr1, arr2, arr3]

Now, if you want a “general solution”, that means how to nest n arrays?

Well, the n arrays are already a “collection” of arrays… it is already nested.

just iterate the arrays and use push/pop/unshift.
(solution assumes all arrays have equal size)

https://apidock.com/ruby/Array/zip

This would work. I’m sure it could be refactored using cleaner methods but I think this is what you are looking for.

arr1 = [10,20,30]

arr2 = [100,200,300]

arr3 = [40,50,60]

result = []

un_merged = [arr1, arr2, arr3]

i_1 = 0

i_2 = 0

while i_2 < un_merged.length            

    arr = []

    while i_1 < un_merged.length        

        arr << un_merged[i_1][i_2]      

        i_1 += 1                       

    end

    result << arr                                

    i_2 += 1 

    i_1 = 0                                                

end

p result

Hi, I tried here.

inp = [arr1, arr2, arr3]
result = (0…inp[0].size).collect{|i| inp.collect{|x| x[i]}}

1 Like

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs