[英]Functional programming with Ruby
Ruby has support for functional programming features like code blocks and higher-level functions (see Array#map, inject, & select). Ruby支持功能性编程功能,例如代码块和高级功能(请参见Array#map,inject和select)。
How can I write functional code in Ruby? 如何用Ruby编写功能代码?
Would appreciate examples like implementing a callback. 将赞赏实现回调的示例。
You could use yield 您可以使用收益
def method(foo,bar)
operation=foo+bar
yield operation
end
then you call it like this: 那么您可以这样称呼它:
foo=1
bar=2
method(foo,bar) {|result| puts "the result of the operation using arguments #{foo} and #{bar} is #{result}"}
the code in the block (a block is basically "a chunk of code" paraphrasing ruby programmers) gets executed in the "yield operation" line, you pass the method a block of code to be executed inside the method defined. 在“ yield operation”行中执行该块中的代码(一个块基本上是用红宝石程序员解释的一个“代码块”),您将该方法传递给要在定义的方法内执行的代码块。 This makes Ruby pretty versatile language. 这使得Ruby非常通用。
In this case yield receives an argument called "operation". 在这种情况下,yield接收一个称为“ operation”的参数。 I wrote it that way because you asked for a way to implement a callback. 我这样写是因为您要求一种实现回调的方法。
but you could just wrote 但是你可以写
def method()
puts "I'm inside the method"
yield
end
method(){puts "I'm inside a block"}
and it would output 它会输出
I'm inside the method
I'm inside a block
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.