Estuche rígido con matriz que usa hases en el interior (ruby)

Yo tengo:
a = [{:a=1,"b=2,:c=3},{:a=4,:b=5,:c=6},..] (including 2 items with 3 keys)
b = [{:d=7},{:d=8},...] (including 2 items with 1 key)

At final I need to have 2 items with 4 keys:
a = [{:a=1,:b=2,:c=3,:d=7},{:a=4,:b=5,:c=6,:d=8},..]

a.each do |item|
b.each do |view|
item.merge!(view)
end
end

But at final I have in two items the same dates as for item one in array b (d=7).

preguntado el 10 de marzo de 12 a las 14:03

{a=1,b=2,c=3} is this hash valid? maybe you meant {:a=>1,:b=>2,:c=>3} -

1 Respuestas

First of all your definitions of a and b are not very valid. You need to use either symbols or strings a is not a valid key for a hash. Also you should use => to point a key to value. Here is how you can achieve what you want to do:

a = [{:a=>1,:b=>2,:c=>3},{:a=>4,:b=>5,:c=>6}]
b =[{:d=>7}, {:d=>8}]
a.zip(b) do |x,y|
x.merge!(y)
end

Zip performs the operation on each matching pair of elements in a and b - precisely what you want.

respondido 10 mar '12, 14:03

Creo que te falta un .map al final de tu zip? - marc talbot

I have tried it in my irb. After execution of the code I have pasted, the contents of a is [{:c=>3, :a=>1, :b=>2, :d=>7}, {:c=>6, :a=>4, :b=>5, :d=>8}], which is what we want. - Ivailo Strandjev

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.