我可以轻松地将一个元素添加到现有数组中:
arr = [1]
arr << 2
# => [1, 2]
如何将多个元素添加到我的数组中?
我想做arr << [2, 3]
之类的事情,但这会为我的数组添加一个数组#=> [1, [2, 3]]
答案 0 :(得分:55)
使用+=
运算符:
arr = [1]
arr += [2, 3]
arr
# => [1, 2, 3]
答案 1 :(得分:28)
.push
arr = [1]
arr.push(2, 3)
# => [1, 2, 3]
您还可以.push()
其他数组的所有元素
second_arr = [2, 3]
arr.push(*second_arr)
# => [1, 2, 3]
但请注意! 如果没有 *
它会将second_array
添加到arr
。
arr.push(second_arr)
# => [1, [2, 3]]
劣质替代方案:
您还可以链接<<
来电:
arr = [1]
arr << 2 << 3
# => [1, 2, 3]
答案 2 :(得分:16)
您也可以使用Array#concat
:
arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]
答案 3 :(得分:7)
有几种方法可以实现这一目标:
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]
一些链接:
答案 4 :(得分:1)
只需使用.flatten
例如,如果你有这个数组
array = [1,2,3,4,5,6]
你这样做
array.push([123,456,789])
array.push([["abc","def"],["ghi","jkl"]])
你的字符串看起来像
array = [[1,2,3,4,5,6],[123,456,789],[["abc","def"],["ghi","jkl"]]]
您需要做的就是
array.flatten!
现在你的阵列想要这个
array = [1,2,3,4,5,6,123,456,789,"abc","def","ghi","jkl"]
答案 5 :(得分:0)
使用Array#insert可以将数组添加到任何位置:
a = [1, 2, 3]
b = [4,5,6]
b.insert(0, *a)
=> [1, 2, 3, 4, 5, 6]
答案 6 :(得分:-1)
另外,对于使用n次项构建数组,可以使用splat(AKA星号,*
):
arr = [true] * 4 # => [true, true, true, true]
您还可以使用splat重复多个元素:
arr = [123,'abc'] * 3 # => [123,'abc',123,'abc',123,'abc']
当然,您可以使用任何数组运算符,例如+:
arr = [true] * 3 + [false] # => [true, true, true, false]
我将其与#sample
结合使用以生成随机加权结果:
arr.sample # => true 3 out of 4 times