How can you change this array:
[["1","one"], ["2","two"], ["3","three"]]
to this?
["1","one"], ["2","two"], ["3","three"]
Clarification
My apologies for giving an invalid second version. This is what I'm really going for:
I want to add ["0","zero"]
to the beginning of [["1","one"], ["2","two"], ["3","three"]]
, to get:
[["0","zero"], ["1","one"], ["2","two"], ["3","three"]]
I have tried:
["0","zero"] << [["1","one"], ["2","two"], ["3","three"]]
The above approach produces this, which contains a nesting I don't want:
[["0","z开发者_如何学Cero"], [["1","one"], ["2","two"], ["3","three"]]]
unshift
ought to do it for you:
a = [["1","one"], ["2","two"], ["3","three"]]
a.unshift(["0", "zero"])
=> [["0", "zero"], ["1", "one"], ["2", "two"], ["3", "three"]]
You are probably looking for flatten:
Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten.
[["1","one"], ["2","two"], ["3","three"]].flatten
Which gives you:
=> ["1", "one", "2", "two", "3", "three"]
[["1","one"], ["2","two"], ["3","three"]].flatten
You need to make your questions clearer, but is the following what you meant?
# 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"]]]
精彩评论