Reputation: 763
Beginner Ruby question here: What's the most idiomatic way to combine two arrays of arrays in Ruby?
a = [[0, 0, 0]]
b = [[1, 1, 1]]
I'd like to find c such that
c = [[0, 0, 0], [1, 1, 1]]
I've been able to solve this with a loop, but can't seem to find a way that "feels" correct.
Upvotes: 0
Views: 78
Reputation: 10769
You could also use concat:
a = [[0, 0, 0]]
b = [[1, 1, 1]]
c = a.concat(b)
c #=> [[0, 0, 0], [1, 1, 1]]
But please note it appends the elements of b
to a
, which might be less expensive than a + b
(new array by concatenating a
and b
) but modifies the a
.
a #=> [[0, 0, 0], [1, 1, 1]]
b #=> [[1, 1, 1]]
c #=> [[0, 0, 0], [1, 1, 1]]
Upvotes: 1
Reputation: 80065
chain is a recently added method on Enumerables
a = [[0, 0, 0]]
b = [[1, 1, 1]]
p a.chain(b).to_a # => [[0, 0, 0], [1, 1, 1]]
Upvotes: 4
Reputation: 11183
Why not just concatenation Array#+, a + b
?
a = [[0, 0, 0]]
b = [[1, 1, 1]]
c = a + b
c #=> [[0, 0, 0], [1, 1, 1]]
Upvotes: 3
Reputation: 52336
One method would be:
c = [a.flatten] + [b.flatten]
although you could also:
c = [a.first] + [b.first]
I expect there are a few other too.
Upvotes: 1