当前位置: 动力学知识库 > 问答 > 编程问答 >

How to reimplement the map method in ruby using recursion?

问题描述:

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!

网友答案:

What is happening in your code is every time you call mymap_recursive(&block) the new_array is being lost. To solve this you must have a way to maintain the new array that is being built recursively. A simple change to your code is including new_array = [] in your method definition, then passing new array each time. Here would be the code with my changes in place:

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

Then when you call

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

If you have any questions over this syntax or anything let me know and I will try my best to explain it!

网友答案:

Another solution which doesn't change the method signature and doesn't mutate any data:

class Array
  def mymap_recursive(&block)
    if empty?
      []
    else
      [block.call(first)] + drop(1).mymap_recursive(&block)
    end
  end
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: