Ruby: how to decorate a method with memoization?

Suppose I have a class in Ruby:

class Test def method(arg1, arg2) return arg1+arg2 end memoize :method end 

And I want to remember his results. Therefore, for debugging purposes, I changed the class as follows:

 class Test def method(arg1, arg2) puts 'sth to make sure the method was executed' return arg1+arg2 end ... end 

And he wrote a test that calls a method with the same arguments to see what is output ... and it's good that the method is not memoized. What is the right way to do this?

+4
source share
2 answers

memoize :method inside the class body, memoizes the Test.method method. However, you want to memoize the instance method of Test#method . To do this, use the memoize :method inside the Test initialization method. (Make sure you first Memoize module in Test ).

+8
source
0
source

Source: https://habr.com/ru/post/1315712/


All Articles