Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails class << self

Tags:

class

ruby

I would like to understand what class << self stands for in the next example.

module Utility   class Options #:nodoc:     class << self       def parse(args)                 end     end   end end 
like image 483
xpepermint Avatar asked Apr 02 '10 16:04

xpepermint


People also ask

What does class << self do in Ruby?

In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self.

What is self keyword in rails?

self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.

What does self refer to in an instance method body?

the method self refers to the object it belongs to. Class definitions are objects too. If you use self inside class definition it refers to the object of class definition (to the class) if you call it inside class method it refers to the class again.


2 Answers

this

module Utility   class Options #:nodoc:     class << self       # we are inside Options's singleton class       def parse(args)        end     end   end end 

is equivalent to:

module Utility   class Options #:nodoc:     def Options.parse(args)      end   end end 

A couple examples to help you understand :

class A   HELLO = 'world'   def self.foo     puts "class method A::foo, HELLO #{HELLO}"   end    def A.bar     puts "class method A::bar, HELLO #{HELLO}"   end    class << self     HELLO = 'universe'     def zim       puts "class method A::zim, HELLO #{HELLO}"     end   end  end A.foo A.bar A.zim puts "A::HELLO #{A::HELLO}"  # Output # class method A::foo, HELLO world # class method A::bar, HELLO world # class method A::zim, HELLO universe # A::HELLO world 
like image 68
maček Avatar answered Oct 11 '22 19:10

maček


This is an eigenclass. This question's been asked before.

like image 39
Frank Shearar Avatar answered Oct 11 '22 19:10

Frank Shearar