Ruby Flatten

Ruby Flatten Methods

How to create the Own Ruby Flatten method instead of using predefined flatten?

Let’s suppose, you have an array of nested, or multidimensional, arrays, that is, an array in which there are elements that are also arrays:array = [1, [2, 3, [4, 5]]]

The flatten method will return a one-dimensional array, an array where all the values are on the same level:
array = [1, [2, 3, [4, 5]]]         
array.flatten #=> [1, 2, 3, 4, 5]

Additionally, you can call the flatten method with an argument, which will flatten that array by that many levels:
array = [1, [2, 3, [4, 5]]]               
array.flatten(1) #=> [1, 2, 3, [4, 5]]

Now let’s write our flattening methods! 

Flattening an Array by One Dimension

We’re going to start by defining a helper method that flattens an array by one dimension:

def single_flatten(array)  
  results = []  
  array.each do |element|    
    if element.class == Array      
      element.each {|value| results << value}    
    else      
       results << element    
    end  
  end 
  results
end
my_array = [1, [2, 3, [4, 5]]]
single_flatten(my_array) #=> [1, 2, 3, [4, 5]]

Flattening an Array n Times

But what if we want to flatten an array a given number of times? We can call single_flatten within a while loop with a counter:

def multiple_flatten(array, n)
  count = 0
  arr = array
  while count < n do
    arr = single_flatten(arr)
    count += 1
  end
  arr
end
my_array = [1, [2, 3, [4, [5, 6]]]]
multiple_flatten(my_array, 2) #=> [1, 2, 3, 4, [5, 6]]

Flattening an Array with Recursion

Our last helper method is the recursive flatten:

def recursive_flatten(array, results = [])
  array.each do |element|
    if element.class == Array
      recursive_flatten(element, results)
    else
      results << element
    end
  end
  results
end
my_array = [1, [2, 3, [4, 5]]]
recursive_flatten(my_array) #=> [1, 2, 3, 4, 5]

Thanks For Reading..

Leave a Reply

Your email address will not be published. Required fields are marked *