你如何在Ruby中添加阵列到另一个阵列而不是一个多维的结果结束了? [英] How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

查看:103
本文介绍了你如何在Ruby中添加阵列到另一个阵列而不是一个多维的结果结束了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  =的someArray [某些,事]anotherarray = [另一个,物]somearray.push(anotherarray.flatten!)

我的预期。

  [一些,事,另,事]


解决方案

您已经有了一个可行的想法,但 #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

这篇关于你如何在Ruby中添加阵列到另一个阵列而不是一个多维的结果结束了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆