I'm a ruby newbie, learning to code. I wanted to understand how some of the methods available from the Enumerable module work. So I'm reimplementing them. One challenge was to implement them using recursion. However, I'm running into a problem when trying to implement the Enumerable#Map method using recursion.
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 figure out why it wasn't working 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 figure out why its not returning one array with all the values.
Thanks for your help!