ruby - 如何在 Ruby 中将一个数组添加到另一个数组而不以多维结果结束?

标签 ruby arrays multidimensional-array

我试过:

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)

我以为

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

但是得到了

["some", "thing", nil]

最佳答案

你有一个可行的想法,但是 #flatten! 放错了地方——它压扁了它的接收器,所以你可以用它来转动 [1, 2, ['foo', 'bar']][1,2,'foo','bar']

我无疑忘记了一些方法,但你可以连接:

a1.concat a2
a1 + a2              # creates a new array, as does a1 += a2

前置/附加:

a1.push(*a2)         # note the asterisk
a2.unshift(*a1)      # note the asterisk, and that a2 is the receiver

拼接:

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

附加并展平:

(a1 << a2).flatten!  # a call to #flatten instead would return a new array

关于ruby - 如何在 Ruby 中将一个数组添加到另一个数组而不以多维结果结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1801516/

相关文章:

ruby-on-rails - 没有为项目配置 ruby​​ 解释器

ruby-on-rails - 在 Model 类方法中指定当前抓取的记录

ruby - 正则表达式在 Ruby 中捕获相同数字的组

arrays - 数组中每个 "_id"的别名

c++ - 使用 int [] 运算符的 3D 数组 C++

c - 在 C 中仅初始化二维数组的一行?

ruby-on-rails - 如何使用 Azure Pipelines 将 Ruby 部署到 Azure 应用服务?

arrays - 如何确定数组中的所有对象是否在 Swift 中连接

c - 为什么我的代码不打印排序数组?

java - 在 Java 中对整数数组进行冒泡排序(递归)时出现问题