ZHH
ZHH

Reputation: 99

Push array into array on ruby by just one level

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

Upvotes: 2

Views: 1759

Answers (6)

huhuhu
huhuhu

Reputation: 199

How about this?

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

Upvotes: 0

Gagan Gami
Gagan Gami

Reputation: 10251

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

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110725

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 

Upvotes: 1

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

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

Upvotes: 1

Kirill
Kirill

Reputation: 1538

What about?

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

Upvotes: 0

sawa
sawa

Reputation: 168209

a.concat(b)

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

Upvotes: 5

Related Questions