0

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.

1
  • Both flatten and flatten(1) have a limatation: [[1],[2]].zip([3,[4,5]]).map { |x| x.flatten(1) } #=> [[1, 3], [2, 4, 5]]. I don't know if that's a problem in your app. If you did not want to alter arrays, you could write [1,2].zip([3,[4,5]]).map { |a,b| [a]+[b] } #=> [[1, 3], [2, [4, 5]]]. Commented Nov 30, 2014 at 1:23

3 Answers 3

2
arrays.zip(new_array).map(&:flatten)
# => [[8300, 6732, 4101, 3137, 3097, 10], [1088, 647, 410, 138, 52, 100], [623, 362, 191, 25, 0, 1000]] 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.