Ruby方法来组合Enumerator和函数

huangapple go评论59阅读模式
英文:

Ruby method to compose Enumerator with function

问题

如果你有一个枚举器和一些可调用对象(proc/lambda/method),有时将它们组合以创建一个新的枚举器会很方便,就像这样:

```ruby
class Enumerator
  def compose func
    Enumerator.new do |yielder|
      each { |x| yielder << func[x] }
    end
  end
end

# 创建一个枚举器,产生0、2、4、6...
(0..10).each.compose(proc { |x| x * 2 })

是否没有内置方法可以做到这一点?或者没有更简单的语法?我一直在查阅文档,因为我们有Enumerator::+Proc::<<,它们接近但不完全正确。


<details>
<summary>英文:</summary>

If you have an enumerator and some callable (proc/lambda/method) it is sometimes handy to compose them to create a new enumerator, like this

```ruby
class Enumerator
  def compose func
    Enumerator.new do |yielder|
      each { |x| yielder &lt;&lt; func[x] }
    end
  end
end

# make an enumerator that yields 0, 2, 4, 6...
(0..10).each.compose(proc { |x| x * 2 })

Is there no built-in method for doing this? Or no simpler syntax? I've been trawling the docs because we have Enumerator::+ and Proc::<< which are close but not quite right.

答案1

得分: 4

这听起来像 Enumerable#map 方法:

(0..10).each.map { |x| x * 2 }

事实上,你甚至不需要 each,因为 map 是混入了 Enumerable 的任何对象上的方法:

(0..10).map { |x| x * 2 }

如果你想要获得一个惰性枚举器,你可以在应用任何转换之前调用 Enumerable#lazy。这将返回一个对象,可以对其应用所有的 Enumerable 方法以惰性方式执行:

(0..10).lazy.map { |x| x * 2 }
英文:

That sounds like Enumerable#map

(0..10).each.map { |x| x * 2 }

In fact, you don't even need the each, since map is a method on anything that mixes in Enumerable.

(0..10).map { |x| x * 2 }

If you want to get a lazy enumerator, you can call Enumerable#lazy before applying any transformations. This returns an object on which all of the Enumerable methods can be applied lazily.

(0..10).lazy.map { |x| x * 2 }

huangapple
  • 本文由 发表于 2023年2月8日 12:14:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定