[英]How do I add multiple elements to an array?
I can easily add one element to an existing array: 我可以轻松地将一个元素添加到现有数组中:
arr = [1]
arr << 2
# => [1, 2]
How would I add multiple elements to my array? 如何将多个元素添加到我的数组?
I'd like to do something like arr << [2, 3]
, but this adds an array to my array #=> [1, [2, 3]]
我想做一些像arr << [2, 3]
这样的东西,但这会为我的数组添加一个数组#=> [1, [2, 3]]
Using +=
operator: 使用+=
运算符:
arr = [1]
arr += [2, 3]
arr
# => [1, 2, 3]
.push
利用.push
arr = [1]
arr.push(2, 3)
# => [1, 2, 3]
You can also .push()
all elements of another array 你也可以.push()
另一个数组的所有元素
second_arr = [2, 3]
arr.push(*second_arr)
# => [1, 2, 3]
But take notice! 但请注意! without the *
it will add the second_array
to arr
. 没有 *
它会将second_array
添加到arr
。
arr.push(second_arr)
# => [1, [2, 3]]
Inferior alternative: 劣质替代方案:
You could also chain the <<
calls: 你也可以链接<<
calls:
arr = [1]
arr << 2 << 3
# => [1, 2, 3]
You can do also as below using Array#concat
: 您也可以使用Array#concat
执行以下操作:
arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]
There is several methods to achieve that: 有几种方法可以实现:
array = [1, 2]
array += [3, 4] # => [1, 2, 3, 4]
# push: put the element at the end of the array
array.push([5, 6]) # => [1, 2, 3, 4, [5, 6]]
array.push(*[7, 8]) # => [1, 2, 3, 4, [5, 6], 7, 8]
array << 9 # => [1, 2, 3, 4, [5, 6], 7, 8, 9]
# unshift: put the element at the beginning of the array:
array.unshift(0) #=> [0, 1, 2, 3, 4, [5, 6], 7, 8, 9]
Some links: 一些链接:
just use .flatten
只需使用.flatten
for example if you have this array 例如,如果你有这个数组
array = [1,2,3,4,5,6]
and you do this 而你这样做
array.push([123,456,789])
array.push([["abc","def"],["ghi","jkl"]])
your string would look something like 你的字符串看起来像
array = [[1,2,3,4,5,6],[123,456,789],[["abc","def"],["ghi","jkl"]]]
all you need to do is 你需要做的就是
array.flatten!
and now your array would like this 现在你的阵列会喜欢这个
array = [1,2,3,4,5,6,123,456,789,"abc","def","ghi","jkl"]
Use Array#insert can add an array to any position: 使用Array#insert可以将数组添加到任何位置:
a = [1, 2, 3]
b = [4,5,6]
b.insert(0, *a)
=> [1, 2, 3, 4, 5, 6]
One more, for building up an array with items n-times you can use the splat (AKA asterisk, *
): 另外,对于使用n次项构建数组,可以使用splat(AKA星号, *
):
arr = [true] * 4 # => [true, true, true, true]
You can also use the splat for repeating multiple elements: 您还可以使用splat重复多个元素:
arr = [123,'abc'] * 3 # => [123,'abc',123,'abc',123,'abc']
Of course, you can use any array operators with that, such as +: 当然,您可以使用任何数组运算符,例如+:
arr = [true] * 3 + [false] # => [true, true, true, false]
I use that in conjunction with #sample
to generate random weighted results: 我将它与#sample
结合使用以生成随机加权结果:
arr.sample # => true 3 out of 4 times
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.