简体   繁体   English

使用Ruby进行函数式编程

[英]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.

相关问题 Ruby函数编程的困惑—(入门) - Ruby functional programming confusion — (Beginner) Ruby中的命令式与功能性编程 - Imperative vs Functional Programming in Ruby 这些“反向”和“扭转”功能如何在 Ruby 中工作? (函数式编程) - How do these 'reverse' and 'twist' functions work in Ruby? (functional programming) 是否存在与Perl或Ruby中的触发器运算符等效的函数式编程概念? - Is there a functional programming concept equivalent to the flip-flop operator in Perl or Ruby? 如何使用ruby中的函数式编程范例重写在动态编程中查找最大连续子数组? - How to rewrite finding max contiguous subarray in Dynamic Programming using functional programming paradigm in ruby? 你能处理Ruby的方法,如函数式编程,比如记忆函数吗? - Can you deal with Ruby's method like functional programming, such as memoizing a function? 从函数式编程的角度看,过滤器异常后Ruby是否会返回另一种类型? - Is Ruby's returning of a different type after a filter unusual from a functional programming perspective? ruby中的功能代码示例 - Functional code examples in ruby Ruby是一种功能语言吗? - Is Ruby a functional language? ruby 包已加载但不起作用 - ruby package loaded but not functional
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM