djburdick
djburdick

Reputation: 11940

in ruby what's the difference between self.method and a method within class << self

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?

Upvotes: 13

Views: 5709

Answers (2)

Steve Jorgensen
Steve Jorgensen

Reputation: 12341

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.

Upvotes: 7

kyanny
kyanny

Reputation: 1241

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

Upvotes: 4

Related Questions