Remove one level of nested array

How can you change this array:

[["1","one"], ["2","two"], ["3","three"]]

to that?

["1","one"], ["2","two"], ["3","three"]

Explanation

I apologize for the unacceptable second version. This is what I'm really going to do:

I want to add ["0","zero"]to the beginning [["1","one"], ["2","two"], ["3","three"]]to get:

[["0","zero"], ["1","one"], ["2","two"], ["3","three"]]

I tried:

["0","zero"] << [["1","one"], ["2","two"], ["3","three"]]

The above approach creates this, which contains the nested I don't want:

[["0","zero"], [["1","one"], ["2","two"], ["3","three"]]]
+3
source share
4 answers

unshift should do it for you:

a = [["1","one"], ["2","two"], ["3","three"]]
a.unshift(["0", "zero"])
=> [["0", "zero"], ["1", "one"], ["2", "two"], ["3", "three"]]
+6
source

You may be looking for flatten :

, (). , , . .

[["1","one"], ["2","two"], ["3","three"]].flatten

:

=> ["1", "one", "2", "two", "3", "three"] 
+1

[["1","one"], ["2","two"], ["3","three"]].flatten

+1
source

You need to make your questions clearer, but the next thing you had in mind?

# 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"]]]
0
source

All Articles