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!
source
share