Ruby 中 Enumerator 类的用途是什么 [英] What is the purpose of the Enumerator class in Ruby

查看:47
本文介绍了Ruby 中 Enumerator 类的用途是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我像这样创建一个枚举器:

If I create an Enumertor like so:

enum = [1,2,3].each => #<Enumerator: [1, 2, 3]:each> 

enum 是一个枚举器.这个对象的目的是什么?我不能这样说:

enum is an Enumerator. What is the purpose of this object? I can't say this:

enum { |i| puts i }

但我可以这样说:

enum.each { |i| puts i }

这似乎是多余的,因为枚举器是用 .each 创建的.它似乎存储了一些关于 each 方法的数据.

That seems redundant, because the Enumerator was created with .each. It seems like it's storing some data regarding the each method.

我不明白这里发生了什么.我确信我们有这个 Enumerator 类是有一些逻辑原因的,但是它可以做什么而 Array 不能呢?我以为它可能是 Array 和其他 Enumerables 的祖先,但似乎不是.Enumerator 类存在的确切原因是什么,它会在什么情况下使用?

I don't understand what's going on here. I'm sure there is some logical reason we have this Enumerator class, but what can it do that an Array can't? I thought maybe it was an ancestor of Array and other Enumerables, but it doesn't seem to be. What exactly is the reason for the existence of the Enumerator class, and in what context would it ever be used?

推荐答案

如果你这样做会发生什么 enum = [1,2,3].each;enum.next?:

What happens if you do enum = [1,2,3].each; enum.next?:

enum = [1,2,3].each
=> #<Enumerator: [1, 2, 3]:each>
enum.next
=> 1
enum.next
=> 2
enum.next
=> 3
enum.next
StopIteration: iteration reached an end

当您有一个执行计算的枚举器(例如素数计算器或斐波那契数列生成器)时,这会很有用.它为您编写代码的方式提供了灵活性.

This can be useful when you have an Enumerator that does a calculation, such as a prime-number calculator, or a Fibonacci-sequence generator. It provides flexibility in how you write your code.

这篇关于Ruby 中 Enumerator 类的用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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