Ruby 中的 ->() { } 是什么? [英] What is ->() { } in Ruby?

查看:50
本文介绍了Ruby 中的 ->() { } 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 Ruby/Rails 应用程序中看到了这个表达式:

I've just seen this expression in a Ruby/Rails app:

def method(a, b = nil, &c)
   c ||= ->(v) { v }

我了解第一部分,但不了解 ->() { ... } 语法.什么意思?

I understand the first part, but not the ->() { ... } syntax. What does it mean?

为简洁起见,已更改变量名称.我尝试搜索,但非字母数字字符显然是 SEO 的噩梦.

The variable names have been changed for briefness. I tried searching, but the non-alphanumeric characters are obviously a nightmare for SEO.

推荐答案

它是一个 lambda 字面量.将块变量放在 () 内,将主体放在 {} 内.

It is a lambda literal. Put the block variables inside () and the body inside {}.

->(x, y){x + y}

在这个例子中,->(v){v} 接受一个参数 v 并返回它,换句话说,它是一个恒等函数.如果一个块被传递给method,那么它被分配给c.如果不是,则身份函数默认分配给 c.

In the example, ->(v){v} takes a single argument v and returns it, in other words, it is an identity function. If a block is passed to method, then that is assigned to c. If not, the identity function is assigned to c as default.

这篇关于Ruby 中的 ->() { } 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆