Ruby: standard recursion patterns

One of the things that I usually use in ruby ​​is recursion patterns. For example, suppose I have an array that can contain arrays as elements of unlimited depth. So for example:

my_array = [1, [2, 3, [4, 5, [6, 7]]]]

I would like to create a method that can smooth an array into [1, 2, 3, 4, 5, 6, 7].

I know that I .flattenwill fulfill this task, but this problem is intended as an example of recursion problems that I regularly encounter - and therefore I am trying to find a more reusable solution.

In short - I guess there is a standard template for this kind of thing, but I can't think of anything particularly elegant. Any ideas appreciated

+5
source share
3 answers

- , . : , ( ) , ( ). , Ruby:

class Array
  def deep_flatten
    flat_map do |item|
      if item.is_a?(Array)
        item.deep_flatten
      else
        [item]
      end
    end
  end
end 

[[[1]], [2, 3], [4, 5, [[6]], 7]].deep_flatten
#=> [1, 2, 3, 4, 5, 6, 7]

? , , , , , recusion , flat_map ( each + concat/push).

+5

, C, , C, .

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-flatten

, Ruby

def flatten values, level=-1
  flat = []
  values.each do |value|
    if level != 0 && value.kind_of?(Array)
      flat.concat(flatten(value, level-1))
    else
      flat << value
    end
  end
  flat
end

p flatten [1, [2, 3, [4, 5, [6, 7]]]] 
#=> [1, 2, 3, 4, 5, 6, 7] 
+4

, .

class Array

  # Monkeypatching the flatten class
  def flatten(new_arr = [])
    self.each do |el|
      if el.is_a?(Array)
        el.flatten(new_arr)
      else
        new_arr << el
      end
    end

    new_arr
  end
end

p flatten [1, [2, 3, [4, 5, [6, 7]]]] 
#=> [1, 2, 3, 4, 5, 6, 7]

, Ruby : ?

+2

All Articles