Why return an enumerator?

arrays, enumerator, ruby

Solution

This completely in accordance with the spirit of 1.9: to return enumerators whenever possible. String#bytes, String#lines, String#codepoints, but also methods like Array#permutation all return an enumerator.

In ruby 1.8 String#to_a resulted in an array of lines, but the method is gone in 1.9.

Problem

I''m curious about why ruby returns an Enumerator instead of an Array for something that seems like Array is an obvious choice. For example: ``` 'foo'.class # => String ``` Most people think of a String as an array of chars. ``` 'foo'.chars.class # => Enumerator ``` So why does String#chars return an Enumerable instead of an Array? I'm assuming somebody put a lot of thought into this and decided that Enumerator is more appropriate but I don't understand why.

Original source