Does Object#to_enum exist?

Hi, all.

I saw someone post a snippet of code that turned an object (with some
sort of “each” method) into an enumerable. It looked really neat, until
I tried:

“abcdef”.to_enum(:each_byte)
NoMethodError: undefined method `to_enum’ for “abcdef”:String
from (irb):1

I looked it up and ri seems to think I have Object#to_enum. The
underlying code is c, so frankly, I don’t understand it. Even running
the examples from the documentation or looking at Object.new.methods, I
see nothing about this elusive method. Does anybody have any insight?
(I’m using ruby 1.8.6.)

Thanks,
Dan

Hi,

In message “Re: does Object#to_enum exist?”
on Thu, 26 Apr 2007 16:45:36 +0900, Dan Z. [email protected]
writes:

|I saw someone post a snippet of code that turned an object (with some
|sort of “each” method) into an enumerable. It looked really neat, until
|I tried:
|
| >> “abcdef”.to_enum(:each_byte)
|NoMethodError: undefined method `to_enum’ for “abcdef”:String
| from (irb):1
| >>
|
|I looked it up and ri seems to think I have Object#to_enum.

It’s available only for 1.9. You can use it with Enumerator
additional library installed.

          matz.

Alle giovedì 26 aprile 2007, Dan Z. ha scritto:

I looked it up and ri seems to think I have Object#to_enum. The
underlying code is c, so frankly, I don’t understand it. Even running
the examples from the documentation or looking at Object.new.methods, I
see nothing about this elusive method. Does anybody have any insight?
(I’m using ruby 1.8.6.)

Thanks,
Dan

You need to require ‘enumerator’. Doing this will result in the to_enum
method
to be added to the Kernel module and to class Object, which mixes Kernel
in.
For example

require ‘enumerator’

“abcdef”.to_enum(:each_byte).each{|b| puts b.chr}
a
b
c
d
e
f

I hope this helps

Stefano

Thank you. I feel silly for making such a newbie-ish mistake, but then
again, I’m a newbie.

Dan

On 4/26/07, Dan Z. [email protected] wrote:

Thank you. I feel silly for making such a newbie-ish mistake, but then
again, I’m a newbie.
It is from our mistakes that we learn, I was about to check for
#to_enum very recently but was too lazy and/or proud to ask, so I
learned too :slight_smile:

Cheers
Robert