Explaining Ruby's Enumerator object

What is Enumerator?

Roughly speaking, the Enumerator object is used when you want to iterate in Ruby. For example, if you add the times method to the number you want to repeat, it becomes an Enumerator object.

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

When you actually want to iterate

Basically, write the 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 i is changing and increasing to 0, 1, 2 and repeating.

Repeat other than block processing

You can also represent blocks with curly braces.

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

When you can write in one line, you may write it like this, so keep in mind.

Recommended Posts

Explaining Ruby's Enumerator object
Explaining Ruby's Symbol object