Push array into array on ruby by just one level

2019-07-10 04:57发布

问题:

Given:

a = [[1,"a"],[2,"b"]]
b = [[3,"c"],[4,"d"]]

I want to turn a into [[1,"a"],[2,"b"][3,"c"],[4,"d"]]. How can do this without +? It creates a new array, which I want to avoid.

(a << b).flatten(1)
# => [1, "a", 2, "b", [3, "c"], [4, "d"]]

回答1:

a.concat(b)

...............................



回答2:

a = [[1,"a"],[2,"b"]]
b = [[3,"c"],[4,"d"]]
a[a.length, 0] = b
a
# > [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]


回答3:

concat is the answer, but you could do this:

a.object_id    #=> 70223889895340
a.replace(a+b) #=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
a              #=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
a.object_id    #=> 70223889895340 


回答4:

> b.inject(a, :<<)
#=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]


回答5:

What about?

a.push(b.shift) while b.any?


回答6:

How about this?

a + b 
=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]