Ruby:如何用记忆来装饰方法?
假设我有一个 Ruby 类:
class Test
def method(arg1, arg2)
return arg1+arg2
end
memoize :method
end
并且我想记住它的结果。因此,出于调试目的,我像这样修改了该类:
class Test
def method(arg1, arg2)
puts 'sth to make sure the method was executed'
return arg1+arg2
end
...
end
并编写了一个测试,使用相同的参数调用该方法,以查看输出的内容......并且该方法没有被记忆。这样做的正确方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
memoize :method
在类主体内,记忆方法Test.method
。但是,您想要记住实例方法Test#method
。为此,请在Test
的初始化方法中使用memoize :method
。 (确保首先将Memoize
模块包含到Test
中)。memoize :method
inside the class body, memoizes the methodTest.method
. However you want to memoize the instance methodTest#method
. To do this usememoize :method
insideTest
's initialize method. (Make sure you include theMemoize
module intoTest
first).有一个关于元编程的截屏视频,其中包含几个记忆示例:
http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming(第 5 集:九个示例)
代码:
http://media.pragprog.com/screencasts/v-dtrubyom/code /v-dtrubyom-v-05-code.tgz
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