0

I have an array of arrays that serves as a table of data, and am trying to add an extra array as though adding an extra column to the table.

For simplicity, suppose the first array is a

a = [["a", "b", "c"], ["e", "f", "g"], ["i", "j", "k"]]

and the second array is b

b = ["d", "h", "l"]

the desired output is:

c = [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

I have tried using + and some attempts at using map but cannot get it

0

3 Answers 3

5

You can zip them together which will create array elements like [["a", "b", "c"], "d"] and then just flatten each element.

a.zip(b).map(&:flatten)
#=> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

Answer improved as per Cary's comment. I think he's done Ruby stuff before.

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

4 Comments

Preference noted, and answer amended, @CarySwoveland
I was not clear. I meant I preferred your answer over the others that had been given at that time.
Thank you for the excellent answers. Can I add a ! somewhere to assign the output as the new a?
Interestingly @CarySwoveland first answer did that (mutate the a array). It was a.zip(b).map{|arr, elem| arr << elem} And he changed it because he thought changing a was undesirable. A bang(!) in my method at map or flatten would only mutate the zip output or the major elements in the zip output, so can't be used for what you want. You could always do simple assignment... a = a.zip(b).map(&:flatten) which would make the intent clear but a would contain a new object. I would be inclined to go for assignment, otherwise, use Cary's solution to mutate the original a object.
4
a.zip(b).map { |arr,e| arr + [e] }
  #=> [["a", "b", "c", "d"],
  #    ["e", "f", "g", "h"],
  #    ["i", "j", "k", "l"]]

The intermediate calculation is as follows.

a.zip(b)
  #=> [[["a", "b", "c"], "d"],
  #    [["e", "f", "g"], "h"],
  #    [["i", "j", "k"], "l"]]

See Array#zip.

3 Comments

Thanks, @Steve. I got that result because my original answer was incorrect.
Your original answer was correct as it returned the right result. However it mutated a in the process.
@Steve, yes. I didn't want it to mutate a or b, so regarded it as incorrect. (Dancing with words.)
0

You can use #each_with_index combined with #map to iterate over the array a and append respective elements of array b

> a.each_with_index.map{|e, i| e | [b[i]] }
=> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

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.