SystematicFrank
SystematicFrank

Reputation: 17261

Difference between self.class and class << self

Trying to find out how private and protected works when used on class methods I came with this code from some other question:

class Bang
    def instance_bang
      self.class.class_bang
    end

    protected
    def self.class_bang
      puts "bang"
    end
end

Calling instance_bang from an instance of Bang works as expected, however I cannot understand what is different in the following code when I take the approach of using class << self.

class Bang
  def instance_bang
    self.class.class_bang
  end

  class << self
    protected 
    def class_bang
      puts "bang"
    end
  end
end

To me, both pieces of code seems to be the same, but the second one fails with NoMethodError claiming that class_bang is protected.

Upvotes: 1

Views: 129

Answers (1)

vidang
vidang

Reputation: 1771

In the second chunk of code, protected is used to specify visibility of methods of Bang class. But 'def self.class_bang' defines a method on the singleton class of Bang, so the protected key will not apply for the method.

In the first chunk of code, you open singleton class of Bang, so protected is used to specify visibility of methods of singleton class of Bang, this means protected will apply for class_bang method. That is why you get the error.

For more information, read this: http://blog.jayfields.com/2006/11/ruby-protected-class-methods.html

Upvotes: 2

Related Questions