Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 memoize its results. So for debug purposes I modified the class like this:

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

And wrote a test that calls the method with same args, to see what get's outputted... and well the method is not memoized. What's the correct way to do this?

like image 507
dahpgjgamgan Avatar asked Feb 27 '23 16:02

dahpgjgamgan


1 Answers

memoize :method inside the class body, memoizes the method Test.method. However you want to memoize the instance method Test#method. To do this use memoize :method inside Test's initialize method. (Make sure you include the Memoize module into Test first).

like image 50
sepp2k Avatar answered Mar 12 '23 11:03

sepp2k