0
votes
 triangular_numbers = Enumerator.new do |yielder|
 number = 0
 count = 1
     loop do
         number += count
         count += 1
         yielder.yield number
     end
 end
 5.times { print triangular_numbers.next, " " }
 puts

I know you all have answers questions about this before.

I am trying to understand more about what going on

Am I right to say yielder is a parameter which is probably a hash or an array and yielder.yield number is basically pushing whatever number it is on to that array.

Also I seen people use yielder << number, i assume that you can also use yielder.push(number), will it do the same thing.

One other thing I like to know why the number is retaining its value.

1

1 Answers

0
votes

No it's not a data structure. It's an object - an instance of Enumerator::Yielder which, if you click the link, you will see isn't documented very well! It is written in C, and the only methods it has are yield and the alias <<. You should leave it to the Ruby core to handle itself.

It's essentially like a pipe, which is used internally by the Enumerator and Enumerable methods to fetch items from an enumeration as required. Enumerator#next, for example, will fetch the next item from the sequence. The methods available in Enumerable are much more comprehensive, and are based on the basic operations provided by Enumerator.