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
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.
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.
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.
module Utility class Options #:nodoc: class << self # we are inside Options's singleton class def parse(args) end end end end
module Utility class Options #:nodoc: def Options.parse(args) end end end
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
This is an eigenclass. This question's been asked before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With