且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何在Ruby中添加阵列到另一个阵列而不是一个多维的结果结束了?

更新时间:2023-11-27 22:34:10

您已经有了一个可行的想法,但 #flatten 是放错了地方! - 它平坦的接收器,所以你可以用它来打开 [1,2,['富','酒吧']] [1, 2,'富','酒吧']

我忘了,无疑一些方法,但你可以连击

  a1.concat A2
A1 + A2#创建新的数组一样,A1 + A2 =

prePEND /追加

  a1.push(* A2)#注意星号
a2.unshift(* A1)#注意星号,而A2是接收器

拼接

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

添加和扁平

 (A1中;< A2).flatten! #调用#flatten而是会返回一个新的数组

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray.push(anotherarray.flatten!)

I expected

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

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

or prepend/append:

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

or splice:

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

or append and flatten:

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