如何更改此数组:
[["1","one"], ["2","two"], ["3","three"]]
到此?
["1","one"], ["2","two"], ["3","three"]
对于提供无效的第二版本表示歉意。这就是我真正想要的:
我想将["0","zero"]
添加到[["1","one"], ["2","two"], ["3","three"]]
的开头,以获取:
[["0","zero"], ["1","one"], ["2","two"], ["3","three"]]
我试过了:
["0","zero"] << [["1","one"], ["2","two"], ["3","three"]]
上面的方法产生了这个,它包含了我不想要的嵌套:
[["0","zero"], [["1","one"], ["2","two"], ["3","three"]]]
答案 0 :(得分:6)
unshift
应该为你做这件事:
a = [["1","one"], ["2","two"], ["3","three"]]
a.unshift(["0", "zero"])
=> [["0", "zero"], ["1", "one"], ["2", "two"], ["3", "three"]]
答案 1 :(得分:3)
您可能正在寻找flatten:
返回一个新数组,该数组是此数组的一维展平(递归)。那 是,对于作为数组的每个元素,将其元素提取到新数组中。如果可选的level参数确定要递展的递归级别。
[["1","one"], ["2","two"], ["3","three"]].flatten
这给了你:
=> ["1", "one", "2", "two", "3", "three"]
答案 2 :(得分:2)
[["1","one"], ["2","two"], ["3","three"]].flatten
答案 3 :(得分:0)
你需要让你的问题更清楚,但你的意思是以下是什么?
# Right answer
original = [["1","one"], ["2","two"]]
items_to_add = [["3","three"], ["4","four"]]
items_to_add.each do |item|
original << item
end
original # => [["1", "one"], ["2", "two"], ["3", "three"], ["4", "four"]]
# Wrong answer
original = [["1","one"], ["2","two"]]
items_to_add = [["3","three"], ["4","four"]]
original << items_to_add # => [["1", "one"], ["2", "two"], [["3", "three"], ["4", "four"]]]