我试着:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我预期的
["some", "thing", "another", "thing"]
但有
["some", "thing", nil]
我试着:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我预期的
["some", "thing", "another", "thing"]
但有
["some", "thing", nil]
当前回答
a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten
这不会去除dups,但是
a|b
删除重复。
其他回答
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray + anotherarray # => ["some", "thing", "another", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
somearray.push(anotherarray).flatten # => ["some", "thing", "another", "thing"]
somearray.push *anotherarray # => ["another", "thing", "another", "thing"]
本质上,问题是“如何在Ruby中连接数组”。自然,答案是使用concat或+,几乎在每个答案中都提到过。
对这个问题的自然扩展是“如何在Ruby中按行执行2D数组的连接”。当我在谷歌上搜索“红宝石串联矩阵”时,这个SO问题是最上面的结果,所以我想我应该把我的答案留给后人(没有问过但相关的)。
在一些应用程序中,你可能想要按行“连接”两个2D数组。类似的,
[[a, b], | [[x], [[a, b, x],
[c, d]] | [y]] => [c, d, y]]
这有点像“增广”矩阵。例如,我使用这种技术创建了一个邻接矩阵来表示一组较小的矩阵中的图。如果没有这种技术,我将不得不以一种容易出错或令人沮丧的方式迭代组件。例如,我可能不得不做一个each_with_index。相反,我将zip和flatten组合如下:
# given two multi-dimensional arrays that you want to concatenate row-wise
m1 = [[:a, :b], [:c, :d]]
m2 = [[:x], [:y]]
m1m2 = m1.zip(m2).map(&:flatten)
# => [[:a, :b, :x], [:c, :d, :y]]
a = ["some", "thing"]
b = ["another", "thing"]
将b追加到a并将结果存储在a中:
a.push(*b)
or
a += b
在这两种情况下,a都变成:
["some", "thing", "another", "thing"]
但在前一种情况下,b的元素被追加到现有的a数组中,在后一种情况下,两个数组连接在一起,结果存储在a中。
Somearray = ["some", "thing"]
Anotherarray = ["another", "thing"]
Somearray + anotherarray
a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten
这不会去除dups,但是
a|b
删除重复。