Calling methods from within singleton class

P

Pat Maddox

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
 
G

George Ogata

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top