views:

271

answers:

6
somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray.push(anotherarray.flatten!)

I expected

["some","thing","another","thing"]
+6  A: 

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

micmoo
+1  A: 

["some", "thing"] + ["another" + "thing"]

samg
+3  A: 

Try this, it will combine your arrays removing duplicates

array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]

array3 = array1|array2

http://www.ruby-doc.org/core/classes/Array.html

Further documentation look at "Set Union"

Joshmattvander
This is an or, it returns an array with no duplicate elements, here is an example of how it probably doesn't do what he is asking, the two "baz" in the first array get turned into one, and the "bar" in the second array doesn't get added.array1 = ["foo", "bar" , "baz" , "baz" ]array2 = ["foo1", "bar1" , "bar" ]array3 = array1|array2array3 # => ["foo", "bar", "baz", "foo1", "bar1"]
Joshua Cheek
+4  A: 

Here are two ways, notice in this case that the first way returns a new array ( translates to somearray = somearray + anotherarray )

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray += anotherarray # => ["some", "thing", "another", "thing"]

somearray = ["some", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
Joshua Cheek
+5  A: 

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 a2
a1 + a2
a1.push(*a2)  # note the asterisk

or splice:

a1[a1.length, 0] = a2
a1[a1.length..0] = a2
a1.insert(a1.length, *a2)

or append and flatten:

(a1 << a2).flatten
pilcrow
well done for being the only one (of 5 I can see) who actually pointed out what was wrong with the code presented. +1
Mike Woodhouse
A: 

I find it easier to push or append arrays and then flatten them in place, like so:

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push anotherarray # => ["some", "thing", ["another", "thing"]]
#or
somearray << anotherarray # => ["some", "thing", ["another", "thing"]]
somearray.flatten!  # => ["some", "thing", "another", "thing"]
somearray # => ["some", "thing", "another", "thing"]
nas