ruby - Ruby 可枚举的辅助 block

标签 ruby lambda

我找不到它的名称,无法了解其工作原理和工作方式的更多信息,但我们发现您可以执行以下操作:

Person = Struct.new(:name)
people = [Person.new('foo'), Person.new('bar')]
# => [#<struct Person name="foo">, #<struct Person name="bar">]
people.find { |person| person.name == 'baz' }
# => nil
people.find(->{ [] }) { |person| person.name == 'baz' }
# => []

我想,每当有东西返回 nil 时,这就是一个失败的 block ,但也许有人可以阐明它是如何工作的?

最佳答案

来自documentation :

find(ifnone = nil) {| obj | block } → obj or nil

find(ifnone = nil) → an_enumerator

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

If no block is given, an enumerator is returned instead.

关于ruby - Ruby 可枚举的辅助 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22309045/

相关文章:

c# - C# MVC 4 中带有 Linq 的 Where 子句

java - 有没有办法减少多个类型参数?

c# - SQL 查询到 Lambda C#

ruby-on-rails -::ModuleName::ClassName 和 ModuleName::ClassName 有什么区别

ruby - 如何确定数组是否包含其中一个元素

ruby - Rails3 : Functional tests fail with NoMethodError: undefined method `user' for nil:NilClass

ruby-on-rails - 部署到 Heroku 时出错(弃用警告 : You have Rails 2. 供应商/插件中的 3 样式插件)

c++ - 在三元运算符中初始化捕获 lambda

python - Tensorflow <lambda>() 获得意外的关键字参数 'partition_info'

ruby - << 和 += 有什么区别?