How to override the map method in ruby ​​using recursion?

I'm new to ruby, learning how to code. I would like to understand how some of the methods available from the Enumerable module work . Therefore, I overestimate them. One of the tasks was to implement them using recursion. However, when I tried to implement the Enumerable # Map method when using recursion, I ran into a problem.

This is my code:

class Array
  def mymap_recursive(&block)
    copy_of_array = dup
    new_array = []
    return new_array if copy_of_array.empty?
    value = copy_of_array.shift
    new_array << yield(value)
    copy_of_array.mymap_recursive(&block)
  end
end

I tried to understand why it does not work, so I put

puts "#{new_array}"

at the end of the method. Then in Sublime Text I did

arr = [2,2,5,5,10]
arr.mymap_recursive {|n| n * n}

After pressing cmd + b, the output I got was:

[100]
[25]
[25]
[4]
[4]

I cannot understand why it does not return a single array with all values.

Thank you for your help!

+4
source share
2 answers

- , mymap_recursive(&block), new_array. , , . new_array = [] , . :

class Array
  def mymap_recursive(new_array = [], &block)
    copy_of_array = self.dup
    return new_array if copy_of_array.empty?
    value = copy_of_array.shift
    new_array << yield(value)
    copy_of_array.mymap_recursive(new_array, &block)
  end
end

,

arr = [2,2,5,5,10]
p arr.mymap_recursive {|n| n * n}
#returns
#[4, 4, 25, 25, 100]

- -, , !

+2

, :

class Array
  def mymap_recursive(&block)
    if empty?
      []
    else
      [block.call(first)] + drop(1).mymap_recursive(&block)
    end
  end
end
+1

All Articles