# Beginner: Add/merge arrays

**URL:** <https://www.ruby-forum.com/t/beginner-add-merge-arrays/142141>\
**Category:** Ruby\
**Created:** [July 3, 2008, 8:14pm UTC](https://www.ruby-forum.com/t/beginner-add-merge-arrays/142141 "2008-07-03T20:14:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![crenner](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/278dde/32.png) [@crenner](https://www.ruby-forum.com/u/crenner)\
**Post date:** [July 3, 2008, 8:14pm UTC](https://www.ruby-forum.com/t/beginner-add-merge-arrays/142141/1 "2008-07-03T20:14:23Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![crenner](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/278dde/32.png) [@crenner](https://www.ruby-forum.com/u/crenner)\
**Post date:** [July 3, 2008, 8:46pm UTC](https://www.ruby-forum.com/t/beginner-add-merge-arrays/142141/2 "2008-07-03T20:46:02Z")

</div>

On Jul 3, 2:11 pm, Chris C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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](http://LearnRuby.com) offers Rails & Ruby HANDS-ON public & ON-SITE  
workshops. Please visit [http://LearnRuby.com](http://LearnRuby.com) for all the details.

---

<div class="post-metadata">

**Author:** ![crenner](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/278dde/32.png) [@crenner](https://www.ruby-forum.com/u/crenner)\
**Post date:** [July 3, 2008, 9:10pm UTC](https://www.ruby-forum.com/t/beginner-add-merge-arrays/142141/3 "2008-07-03T21:10:18Z")

</div>

Hi Eric,

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

Cheers, Chris
