Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Beginner: Add/merge arrays
Chris Chris
7/3/2008 6:11:00 PM
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
--
Posted via
http://www.ruby-...
.
2 Answers
Eric I.
7/3/2008 6:40:00 PM
0
On Jul 3, 2:11 pm, Chris Chris <kyl...@gmx.net> wrote:
> 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://Lea...
for all the details.
Chris Chris
7/3/2008 7:07:00 PM
0
Hi Eric,
thanks for your help... Very helpful that you included all the steps,
too!
Cheers, Chris
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Beginner: Add/merge arrays
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password