Beginner: Add/merge arrays

C

Chris Chris

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
 
E

Eric I.

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

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.
 
C

Chris Chris

Hi Eric,

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

Cheers, Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,269
Latest member
vinaykumar_nevatia23

Latest Threads

Top