ES6’s Generator Function and Ruby’s Enumerator. What they are?

1 minute read

Javascript ES6 Generator Function

Check its docs.

Declaring the fn:

function* foo(){  // NOTE: the *. It declares this is as a generator fn
  var index = 0;
  while (index <= 2)
    yield index++;

Calling the iterator fn:

var iterator = foo();  // calling it returns an iterator; // { value: 0, done: false }; // { value: 1, done: false }; // { value: 2, done: false }; // { value: undefined, done: true }

Ruby’s Enumerator

Check its docs.

Declaring the fn:

def foo
  index = -1
  yield(index += 1) while index < 2

Note: In ruby, if you simply call this function (with a block), it will behave as a normal function. You need to do this to convert this function to an enumerator:

enum = to_enum(:foo)

Calling the enumerator fn:

p # 0
p # 1
p # 2
p # raises StopIteration exception, saying iteration reached end


As you can see, ES6 offers the same enumerator functionality that’s already present in Ruby. If you can grasp one, you can grasp the other easily.

What purpose does it serve?

The enumerator capability allows the caller to have the execution control of a function. We are literally saying “continue”, and then after some time, “freeze!”. The function stops right where it was at that point, and we can continue and play this till the end of execution!

Ruby also provides a way to rewind the enumerator back to the start once it had reached the end.

Avdi Grimm’s Rubytapas episode on this covers the enumerator’s usage in more detail. Check it out, it’s totally free!