你如何在 Ruby 中将一个数组添加到另一个数组而不是得到多维结果? [英] How do you add an array to another array in Ruby and not end up with a multi-dimensional result?
本文介绍了你如何在 Ruby 中将一个数组添加到另一个数组而不是得到多维结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我预料到了
["some","thing","another","thing"]
推荐答案
你有一个可行的想法,但 #flatten!
是在错误的地方——它压平了它的接收器,所以你可以用它把[1, 2, ['foo', 'bar']]
变成[1,2,'foo','bar']
.
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 # 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 中将一个数组添加到另一个数组而不是得到多维结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文