How do you add an array to another array in Ruby and not end up with a multi-dimensional result?
You've got a workable idea, but the #flatten!
is in the wrong place -- it flattens its receiver, so you could use it to turn [1, 2, ['foo', 'bar']]
into [1,2,'foo','bar']
.
I'm doubtless forgetting some approaches, but you can concatenate:
a1.concat a2a1 + a2 # creates a new array, as does a1 += a2
or prepend/append:
a1.push(*a2) # note the asteriska2.unshift(*a1) # note the asterisk, and that a2 is the receiver
or splice:
a1[a1.length, 0] = a2a1[a1.length..0] = a2a1.insert(a1.length, *a2)
or append and flatten:
(a1 << a2).flatten! # a call to #flatten instead would return a new array
You can just use the +
operator!
irb(main):001:0> a = [1,2]=> [1, 2]irb(main):002:0> b = [3,4]=> [3, 4]irb(main):003:0> a + b=> [1, 2, 3, 4]
You can read all about the array class here:http://ruby-doc.org/core/classes/Array.html
The cleanest approach is to use the Array#concat method; it will not create a new array (unlike Array#+ which will do the same thing but create a new array).
Straight from the docs (http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-concat):
concat(other_ary)
Appends the elements of other_ary to self.
So
[1,2].concat([3,4]) #=> [1,2,3,4]
Array#concat will not flatten a multidimensional array if it is passed in as an argument. You'll need to handle that separately:
arr= [3,[4,5]]arr= arr.flatten #=> [3,4,5][1,2].concat(arr) #=> [1,2,3,4,5]
Lastly, you can use our corelib gem (https://github.com/corlewsolutions/corelib) which adds useful helpers to the Ruby core classes. In particular we have an Array#add_all method which will automatically flatten multidimensional arrays before executing the concat.