开发者

Ruby: how to decorate a method with memoization?

开发者 https://www.devze.com 2023-01-07 21:05 出处:网络
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:

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
开发者_如何学Python  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?


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).


There's a screencast on metaprogramming with several examples for memoization:

http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming (Episode 5: Nine Examples)

Code:

http://media.pragprog.com/screencasts/v-dtrubyom/code/v-dtrubyom-v-05-code.tgz

0

精彩评论

暂无评论...
验证码 换一张
取 消