Create Your Own Flatten Method in Ruby Program - Run With Code

Latest

Learn Ruby On Rails , Linux and IoT(Internet Of Things).

Amazon

Monday 24 February 2020

Create Your Own Flatten Method in Ruby Program

Ruby Flatten Method


Ruby Program



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

For more detail and Reference https://medium.com/@anneeb/recreating-the-flatten-method-for-arrays-in-ruby-fae8040bdbde and https://www.runwithcode.com/create-your-own-flatten-method-in-ruby-program/


No comments:

Post a Comment

Please do not enter any spam link in the comment box.