Beginner: Add/merge arrays

Hi,

just started working with Ruby (and, well, programming in general :-)…

I have two arrays in Ruby that I’d like to merge:

Array 1:
[“7.99”, “6.99”, “10.99”, “5.97”]

Array 2:
[[“A”, “5”], [“B”, “5”], [“C”, “4”], [“D”, “5”]]

I want to merge those two arrays and as a result get
Array 3:
[[“A”, “5”, “7.99”], [“B”, “5”, “6.99”], [“C”, “4”, “10.99”], [“D”, “5”,
“5.97”]]

Thank you for your help!

Cheers,
Chris

On Jul 3, 2:11 pm, Chris C. [email protected] wrote:

[[“A”, “5”], [“B”, “5”], [“C”, “4”], [“D”, “5”]]

I want to merge those two arrays and as a result get
Array 3:
[[“A”, “5”, “7.99”], [“B”, “5”, “6.99”], [“C”, “4”, “10.99”], [“D”, “5”,
“5.97”]]

Hi Chris,

I realize this is just a sample to help us understand what you’re
after, but are you sure you want to store the string “4” in your array
rather than the integer 4? Same goes with the “10.99”.

Here’s some code that’ll do what you’re after:

a1 = [“7.99”, “6.99”, “10.99”, “5.97”]
a2 = [[“A”, “5”], [“B”, “5”], [“C”, “4”], [“D”, “5”]]

p a1.zip(a2)

oops, we want “7.99” to be at same depth as “A”

p a1.zip(a2).map { |e| e.flatten }

oops, we want “7.99” to come after “5”

p a2.zip(a1).map { |e| e.flatten }

finally!

Hope that helps,

Eric

====

LearnRuby.com offers Rails & Ruby HANDS-ON public & ON-SITE
workshops. Please visit http://LearnRuby.com for all the details.

Hi Eric,

thanks for your help… Very helpful that you included all the steps,
too!

Cheers, Chris