Enumerator :: Yielder#yield方法什么时候有用? [英] When is the Enumerator::Yielder#yield method useful?

查看:100
本文介绍了Enumerator :: Yielder#yield方法什么时候有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题含义yield "提到了Enumerator::Yielder#yield方法.我以前从未使用过它,想知道它在什么情况下会有用.

The question "Meaning of the word yield" mentions the Enumerator::Yielder#yield method. I haven't used it before, and wonder under what circumstances it would be useful.

当您要创建物品的无限列表(例如Eratosthenes筛子)以及需要使用外部迭代器时,它主要有用吗?

Is it mainly useful when you want to create an infinite list of items, such as the Sieve of Eratosthenes, and when you need to use an external iterator?

推荐答案

"

"How to create an infinite enumerable of Times?" talks about constructing and lazy iterators, but my favorite usage is wrapping an existing Enumerable with additional functionality (any enumerable, without needing to know what it really is, whether it's infinite or not etc).

一个简单的示例将实现each_with_index方法(或更普遍的是with_index方法):

A trivial example would be implementing the each_with_index method (or, more generally, with_index method):

module Enumerable
  def my_with_index
    Enumerator.new do |yielder|
      i = 0
      self.each do |e|
        yielder.yield e, i
        i += 1
      end
    end
  end

  def my_each_with_index
    self.my_with_index.each do |e, i|
      yield e, i
    end
  end
end

[:foo, :bar, :baz].my_each_with_index do |e,i|
  puts "#{i}: #{e}"
end
#=>0: foo
#=>1: bar
#=>2: baz

扩展到核心库中尚未实现的功能,例如将给定数组中的值循环分配给每个可枚举的元素(例如,为表行着色):

Extending to something not already implemented in the core library, such as cyclically assigning value from a given array to each enumerable element (say, for coloring table rows):

module Enumerable
  def with_cycle values
    Enumerator.new do |yielder|
      self.each do |e|
        v = values.shift
        yielder.yield e, v
        values.push v
      end
    end
  end
end

p (1..10).with_cycle([:red, :green, :blue]).to_a # works with any Enumerable, such as Range
#=>[[1, :red], [2, :green], [3, :blue], [4, :red], [5, :green], [6, :blue], [7, :red], [8, :green], [9, :blue], [10, :red]]

重点是这些方法返回一个Enumerator,然后将其与常用的Enumerable方法结合使用,例如selectmapinject等.

The whole point is that these methods return an Enumerator, which you then combine with the usual Enumerable methods, such as select, map, inject etc.

这篇关于Enumerator :: Yielder#yield方法什么时候有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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