Forum: Ruby class << self idiom

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D4e855a28dbcc327042084be99f6147b?d=identicon&s=25 surge (Guest)
on 2007-06-20 23:40
(Received via mailing list)
Hello,

I have trouble understanding the need for the class << self idiom. For
example, let's say I have this class:

class My_Class
 def method_1
 end
end

Now, I want to extend that class. I can do:

class My_Class
 def method_2
 end
end

or:

class My_Class
 class << self
   def method_2
   end
 end
end

I understand that in the second case we're extending the singleton
class of My_Class, but why is the second form so often used in Ruby
vs. the other form? Isn't the end result identical?
E0526a6bf302e77598ef142d91bdd31c?d=identicon&s=25 Daniel DeLorme (Guest)
on 2007-06-21 00:56
(Received via mailing list)
surge wrote:
>  class << self
>    def method_2
>    end
>  end
> end
>
> I understand that in the second case we're extending the singleton
> class of My_Class, but why is the second form so often used in Ruby
> vs. the other form? Isn't the end result identical?

They are *not* identical. The first defines an *instance* method
(My_Class.new.method_2); the second defines a *class* method
(My_Class.method_2

Now, there are other ways of defining class methods. Which one you use
depends a lot on personal preference but depends also on constants
(which have a static scope) ->

  class Foo
    K = "foo"
  end

  #can access K
  class Foo
    class << self
      def foo1; K; end
    end
    def self.foo2; K; end
    def Foo.foo3; K; end
  end

  #must specify Foo::K
  class << Foo
    def foo4; Foo::K; end
  end
  def Foo.foo5; Foo::K; end


Daniel
D4e855a28dbcc327042084be99f6147b?d=identicon&s=25 surge (Guest)
on 2007-06-21 01:21
(Received via mailing list)
You're completely right and I understand my mistake now. Thanks for
the comprehensive answer.

Surge
This topic is locked and can not be replied to.