Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flatten an array in Ruby?

Tags:

ruby

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"]] ]

like image 285
Eliasz Łukasz Avatar asked Nov 23 '17 10:11

Eliasz Łukasz


People also ask

What is array flatten method in Ruby?

We will try to understand it with the help of syntax and demonstrating program codes. This method is one of the examples of the Public instance method which is specially defined in the Ruby library for Array class. This method is used to flatten the Array instances.

How do you flatten an array recursively?

Returns a new array that is a one-dimensional flattening of self (recursively). That is, for every element that is an array, extract its elements into the new array. The optional level argument determines the level of recursion to flatten.

What is the return value of flatten in Ruby?

The flatten () is an inbuilt method in Ruby returns a new set that is a copy of the set, flattening each containing set recursively. Parameters: The function does not takes any parameter. Return Value: It returns a boolean value. It returns true if the set is empty or it returns false.

What does it mean to flatten an array?

As the recruiter then explained, flattening an array is the process of taking nested array elements and basically putting them all into one “flat” array. All I have to do is turn some small arrays into one big array.


1 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"]]
like image 95
Santhosh Avatar answered Nov 21 '22 11:11

Santhosh