【发布时间】:2012-09-27 17:14:21
【问题描述】:
我想在变量中存储一个“代码块”以供重复使用,例如:
block = do
|test| puts test
end
3.upto(8) block
谁能告诉我我做错了什么? (或者如果这是不可能的)
【问题讨论】:
我想在变量中存储一个“代码块”以供重复使用,例如:
block = do
|test| puts test
end
3.upto(8) block
谁能告诉我我做错了什么? (或者如果这是不可能的)
【问题讨论】:
在 Ruby 中有很多方法可以做到这一点,其中一种是使用 Proc:
foo = Proc.new do |test|
puts test
end
3.upto(8) { foo.call("hello world") }
阅读有关 Procs 的更多信息:
更新,上面的方法可以改写如下:
# using lower-case **proc** syntax, all on one line
foo = proc { |test| puts test }
3.upto(8) { foo.call("hello world") }
# using lambda, just switch the method name from proc to lambda
bar = lambda { |test| puts test }
3.upto(8) { bar.call("hello world") }
它们基本上是非常相似的方法,只是有细微的差别。
最后,可能有更优雅的方法来做我所概述的事情,很高兴听到任何有更好方法的人的意见。希望这会有所帮助。
【讨论】: