Ruby: select/find 没有块有什么用?

Ruby: Is there any use for select/find without a block?

我有一个懒惰的评估,我想要映射操作产生的第一个真实结果,我又一次发现自己在表达式的末尾写了 .find { |e| e }

这是一个简单的例子;当然,数组和映射块在我的现实生活中是不同的:

[nil, 2, 3, 4].lazy.map{ |e| e }.find { |e| e }

当我必须将块 { |e| e } 添加到 selectfind 时,我总是有点 surprised/disappointed,特别是如果它是一个懒惰的评估,因为两者 - 冗余 - 默认情况下似乎是身份函数:

> [nil, 2, 3, 4].find { |e| e } 
 => 2
> [nil, 2, 3, 4].find
 => #<Enumerator: [nil, 2, 3, 4]:find>
> [nil, 2, 3, 4].find.map { |e| e }
 => [nil, 2, 3, 4] 

这个枚举器实际上与从 .each 获得的枚举器有什么不同吗?

> [nil, 2, 3, 4].each.map { |e| e }
 => [nil, 2, 3, 4] 

select 类似,只是对 lazy 更无益:

> [nil, 2, 3, 4].select
 => #<Enumerator: [nil, 2, 3, 4]:select>
> [nil, 2, 3, 4].select { |e| e }
 => [2, 3, 4]
> [nil, 2, 3, 4].select.lazy.force   # doing it wrong looks functional!
 => [nil, 2, 3, 4] 
> [nil, 2, 3, 4].lazy.select { |e| e }.force
 => [2, 3, 4]
> [nil, 2, 3, 4].lazy.select.force   # same without .force
ArgumentError: tried to call lazy select without a block

这些明显的身份(和 ArgumentError!)是否有用,或者只是在 Ruby 的未来版本中更好地默认设置的机会?

首先 - 一个小小的评论。如果您发现自己键入 { |e| e },您可以改用 &:itself.


除此之外,没有块的可枚举方法通常 return 一个枚举数。您可以使用它来链接枚举器方法。例如,考虑:

[1, 2, 3].map.with_index  { |n, i| n + i } # => [1, 3, 5]
[1, 2, 3].each.with_index { |n, i| n + i } # => [1, 2, 3]

[1, 2, 3].select.with_index { |n, i| (n + 2 * i).even? } # => [2]