2 ruby metaprogramming lazy-evaluation
我想要一个像foo.method1.method2.method3那样向后运行函数的类,我希望函数运行method3 method2然后运行method1.但现在它已经进入了1 2 3.我认为这被称为懒惰评估,但我不确定.
我对Ruby几乎一无所知所以请原谅这个问题,如果它很简单,我已经知道了.
小智 5
当然你可以做到.这听起来像是在正确的路径上思考您只需要使用运行排队方法的方法结束每个方法调用列表的惰性求值.
class Foo
def initialize
@command_queue = []
end
def method1
@command_queue << :_method1
self
end
def method2
@command_queue << :_method2
self
end
def method3
@command_queue << :_method3
self
end
def exec
@command_queue.reverse.map do |command|
self.send(command)
end
@command_queue = []
end
private
def _method1
puts "method1"
end
def _method2
puts "method2"
end
def _method3
puts "method3"
end
end
foo = Foo.new
foo.method1.method2.method3.exec
method3
method2
method1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |