Calling methods from within singleton class

Discussion in 'Ruby' started by Pat Maddox, Nov 25, 2006.

  1. Pat Maddox

    Pat Maddox Guest

    I'd like some clarification on the following simple examples.

    class Foo
    self
    end # Foo

    class << Foo
    self
    end # #<Class:Foo>

    No surprise there. In the first case I'm defining the class and
    returning self, which of course is the class, and in the second it's
    the singleton class.

    class << Foo
    def foo
    "foo"
    end
    end

    Now I can call Foo.foo as expected. It could have just as easily been
    def Foo.foo
    "foo"
    end

    However, I can't do
    class << Foo
    foo
    end

    to call it. It results in "NameError: undefined local variable or
    method `foo' for #<Class:Foo>". What's the difference?

    Pat
    Pat Maddox, Nov 25, 2006
    #1
    1. Advertising

  2. Pat Maddox

    George Ogata Guest

    On 11/25/06, Pat Maddox <> wrote:
    >
    > class << Foo
    > def foo
    > "foo"
    > end
    > end


    This defines a `foo' method on instances of Foo's singleton class, namely Foo.

    > class << Foo
    > foo
    > end
    >
    > ... NameError ...


    This calls `foo' on Foo's singleton class, not Foo.

    Note that "#<Class:Foo>" is #inspect-ese for "Foo's singleton class",
    not "Foo"... ;-)

    G.
    George Ogata, Nov 26, 2006
    #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. Oltmans
    Replies:
    6
    Views:
    341
    Terry Reedy
    Mar 11, 2009
  2. Paul McMahon
    Replies:
    3
    Views:
    205
    David A. Black
    Jun 9, 2008
  3. Kenneth McDonald
    Replies:
    5
    Views:
    313
    Kenneth McDonald
    Sep 26, 2008
  4. Daniel DeLorme
    Replies:
    14
    Views:
    245
    Brian Candler
    Dec 14, 2008
  5. Charles Oliver Nutter

    Singleton methods without the singleton class

    Charles Oliver Nutter, Mar 15, 2010, in forum: Ruby
    Replies:
    4
    Views:
    202
    Charles Oliver Nutter
    Mar 22, 2010
Loading...

Share This Page