does Object#to_enum exist?

Discussion in 'Ruby' started by Dan Zwell, Apr 26, 2007.

  1. Dan Zwell

    Dan Zwell Guest

    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
     
    Dan Zwell, Apr 26, 2007
    #1
    1. Advertising

  2. Alle gioved=EC 26 aprile 2007, Dan Zwell ha scritto:
    > 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


    You need to require 'enumerator'. Doing this will result in the to_enum met=
    hod=20
    to be added to the Kernel module and to class Object, which mixes Kernel in=
    =2E=20
    =46or example

    require 'enumerator'

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

    I hope this helps

    Stefano
     
    Stefano Crocco, Apr 26, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bill Johnson
    Replies:
    0
    Views:
    1,256
    Bill Johnson
    Jul 8, 2005
  2. Y.S.
    Replies:
    3
    Views:
    1,082
    strajan
    Sep 17, 2003
  3. LT
    Replies:
    7
    Views:
    2,147
    Phlip
    Jul 25, 2004
  4. Vahagn Hayrapetyan

    Calling to_enum on a MatchData object

    Vahagn Hayrapetyan, Apr 8, 2011, in forum: Ruby
    Replies:
    14
    Views:
    243
    Vahagn Hayrapetyan
    Apr 14, 2011
  5. Markus Mohr
    Replies:
    7
    Views:
    275
    Thomas 'PointedEars' Lahn
    Nov 28, 2003
Loading...

Share This Page