ironsand
ironsand

Reputation: 15141

How to add an array to a two dimensional array

I want to add an array to a two dimensional array like this:

arrays = [[8300, 6732, 4101, 3137, 3097], [1088, 647, 410, 138, 52], [623, 362, 191, 25, 0]]
new_array = [10, 100, 1000]
arrays.map.with_index{|v,i| v << new_array[i]}
# => [[8300, 6732, 4101, 3137, 3097, 10], [1088, 647, 410, 138, 52, 100], [623, 362, 191, 25, 0, 1000]]

It works well, but I want to know if there is more simpler way to accomplish this behavior.

I appreciate any suggestion.

Upvotes: 0

Views: 61

Answers (3)

Qaisar Nadeem
Qaisar Nadeem

Reputation: 2434

Just a little extension to Santosh answer. If there are nested arrays and you want to the result to be as nested as in original arrays like

arrays = [[8300, [6732], 4101, [3137], 3097], [1088, [647], 410, 138, 52], [623, [362], 191, 25, 0]]
new_array = [10, [100], 1000]

required_answer = [[8300, [6732], 4101, [3137], 3097, 10], [1088, [647], 410, 138, 52, 100], [623, [362], 191, 25, 0, 1000]] 

then you can use

arrays.zip(new_array).map{|x| x.flatten(1)}

this will flatten the array to one level.

Upvotes: 1

Santhosh
Santhosh

Reputation: 29114

arrays.zip(new_array).map(&:flatten)
# => [[8300, 6732, 4101, 3137, 3097, 10], [1088, 647, 410, 138, 52, 100], [623, 362, 191, 25, 0, 1000]] 

Upvotes: 2

Uri Agassi
Uri Agassi

Reputation: 37409

You can use zip:

arrays.zip(new_array).each { |arr, item| arr << item }
arrays
# =>  [[8300, 6732, 4101, 3137, 3097, 10], [1088, 647, 410, 138, 52, 100], [623, 362, 191, 25, 0, 1000]]

Upvotes: 1

Related Questions