How do I flatten an array in Ruby?

Viewed 16870

On Ruby. I have array of array c = [["a"], ["b"]]

How convert it to c = a + b

c = ["a", "b"]

for any array. Maybe it is possible not using other variables. All array inside not flatten.

d = [ [["a"], ["b"]], [["c"], ["d"]], [["e"], ["f"]] ] 

I need [ [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]] ]

3 Answers

Array#flatten also accepts a parameter.

The optional level argument determines the level of recursion to flatten.

c = [[["a"]], [["b"]]]

c.flatten
# => ["a", "b"]

c.flatten(1)
# => [["a"], ["b"]]

Use 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.

irb(main):001:0> a =  [["a"], ["b"]]
=> [["a"], ["b"]]
irb(main):002:0> a.flatten
=> ["a", "b"]

You can control level of recursion flatten(n):

irb(main):001:0> c = [[["a"]], [["b"]]]
=> [[["a"]], [["b"]]]
irb(main):002:0> c.flatten 1
=> [["a"], ["b"]]
irb(main):003:0> 

Ruby:

c = [["a"], ["b"]]

Convert Array of array to Array

c.flatten

To get the sum of array of array

c.flatten.sum
Related