views:

202

answers:

2

Hi,

I've been researching the similarities/differences between Ruby and Python generators (known as Enumerators in Ruby), and so far as i can tell they're pretty much equivalent.

However one difference i've noticed is that Python Generators support a close() method whereas Ruby Generators do not. From the Python docs the close() method is said to do the following:

Raises a GeneratorExit at the point where the generator function was paused. If the generator function then raises StopIteration (by exiting normally, or due to already being closed) or GeneratorExit (by not catching the exception), close returns to its caller."

Is there a good reason why Ruby Enumerators don't support the close() method? Or is it an accidental omission?

I also discovered that Ruby Enumerators support a rewind() method yet Python generators do not...is there a reason for this too?

Thanks

+1  A: 

Generators are stack based, Ruby's Enumerators are often specialised (at the interpreter level) and not stack based.

raggi
A: 

Ruby's Enumerator's use StopIteration class internally, see http://stackoverflow.com/questions/1436037/how-do-enumerators-work-in-ruby-1-9-1

(it's just wrapped if you use it in a for each call). So I'd say they'are a rather close. That being said, I'm not sure what a close method on an enumerator should do, exactly...cleanup, perhaps? (Python's generators probably would benefit from a rewind--note well that in Ruby, some enumerators don't respond to rewind, so they raise an exception when you call that method).

rogerdpack
thanks for your answer. But `StopIteration` is what python uses too - in fact Ruby took this idea from Python hehe. As Regards what a `close()` might do, look to intuited's comment to my question (above).
banister
yeah ruby 1.9.x's Enumerator basically brought it into line with Python's Generator (though you can also just use a block in Ruby to simulate a generator, really).
rogerdpack