Ruby 中 Enumerator 类的用途是什么

编程入门 行业动态 更新时间:2024-10-25 22:36:19
本文介绍了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 类的用途是什么

本文发布于:2023-11-25 17:26:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用途   Ruby   Enumerator

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!