【问题标题】:Functional programming with Ruby使用 Ruby 进行函数式编程
【发布时间】:2016-12-29 00:43:01
【问题描述】:

Ruby 支持函数式编程功能,例如代码块和高级函数(请参阅 Array#map、inject 和 select)。

如何在 Ruby 中编写函数式代码?

希望有实现回调之类的示例。

【问题讨论】:

标签: ruby functional-programming


【解决方案1】:

你可以使用yield

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

【讨论】:

    猜你喜欢
    • 2018-05-04
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多