gpt4 book ai didi

Ruby:没有 block 的选择/查找有什么用吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:31 26 4
gpt4 key购买 nike

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

这是一个简单的例子; array 和 map block 在我的现实生活中当然是不同的:

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

当我必须添加 block 时,我总是有点惊讶/失望 { |e| e } selectfind,特别是如果它是惰性求值,因为两者 - 冗余 - 默认情况下似乎是恒等函数:

> [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


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

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

关于Ruby:没有 block 的选择/查找有什么用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41059681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com