Ruby 支持函数式编程特性,如代码块和更高级别的函数(请参阅 Array#map、inject 和 select)。
如何在 Ruby 中编写函数式代码?
会欣赏像实现回调这样的例子。
Ruby 支持函数式编程特性,如代码块和更高级别的函数(请参阅 Array#map、inject 和 select)。
如何在 Ruby 中编写函数式代码?
会欣赏像实现回调这样的例子。
你可以使用产量
def method(foo,bar)
operation=foo+bar
yield operation
end
然后你这样称呼它:
foo=1
bar=2
method(foo,bar) {|result| puts "the result of the operation using arguments #{foo} and #{bar} is #{result}"}
块中的代码(一个块基本上是“一段代码”,解释 ruby 程序员)在“yield operation”行中执行,你向方法传递一个要在定义的方法内执行的代码块。这使得 Ruby 成为一种非常通用的语言。
在这种情况下,yield 接收一个称为“操作”的参数。我这样写是因为您要求一种实现回调的方法。
但你可以写
def method()
puts "I'm inside the method"
yield
end
method(){puts "I'm inside a block"}
它会输出
I'm inside the method
I'm inside a block