13
class Foo

  def self.one; 1 end

  class << self
    def two; 2 end
  end

end
puts Foo.singleton_methods.inspect # => ["two", "one"]

I've been told the above methods "one" and "two" are conceptually different but I don't see how. They are both singleton methods - what's the difference in concept and also application?

1
  • 1
    +1. What about module_function? I am interested to know the difference from that as well.
    – sawa
    Commented Apr 1, 2011 at 2:29

2 Answers 2

7

In application, there is no difference. In concept, the difference is subtle, but in the first case, you are operating in the current context, and defining a method on another class instance (actually, an instance method in its Eigenclass), whereas in the second case, you are entering the context of the the metaclass ("Eigenclass") of other class instance, and then defining an instance method.

Edit:

I should add that the reasons for choosing the class << self in some cases are...

  1. Cleaner syntax when defining more than a few class-methods.
  2. You can execute other kinds of code in the Eigenclass context besides just def my_method .... You can, for instance, say attr_accessor :some_attribute in that block of code.
4

I strongly recommend you to read "Metaprogramming Ruby". This book explains about Ruby's object model, including singleton method and singleton class.

http://pragprog.com/titles/ppmetr/metaprogramming-ruby

This article also explains same topic.

http://www.contextualdevelopment.com/articles/2008/ruby-singleton

2
  • I actually got my code snippet from that link you sent, as I was still confused after that article. Excerpt "While some object oriented languages have class structures that support both instance methods and class methods (sometimes called static methods), Ruby only supports instance methods. If Ruby only supports instances methods, where do all those class methods you've been creating end up? Why, the singleton class of course." To me that's saying the self.method is the same - ie they are all singletons
    – djburdick
    Commented Apr 1, 2011 at 5:33
  • Ruby supports only instance methods, but a class is also an instance of the Class class. When you add methods to an instance (including Class instance, which is to say, a class) you are really changing the instance's class to a new anonymous subclass of what it was, and then adding a new instance method to that subclass. That anonymous subclass is frequently referred to as the Eigenclass. Commented Apr 1, 2011 at 7:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.