iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💎

Understanding Ruby's Enumerator Object

に公開

What is an Enumerator?

Roughly speaking, an Enumerator object is used when you want to perform iterations in Ruby.
For example, if you append the times method to a number representing how many times you want to repeat, it becomes an Enumerator object.
Note: This explanation is not complete, but it should be enough to grasp the concept.

irb(main):031:0> 3.times
=> #<Enumerator: 3:times>

When you actually want to perform iteration

Basically, you describe a block while using the Enumerator object.

irb(main):035:1* 3.times do |i|
irb(main):036:1*   puts i
irb(main):037:0> end
0
1
2
=> 3

You can see that the iteration is being performed as i increases from 0, 1, to 2.

Iteration other than block processing

You can also represent a block using curly braces.

irb(main):038:0> 3.times { |num| puts num }
0
1
2
=> 3

Keep this in mind, as this style is sometimes used when the code can be written in a single line.

Discussion