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.
self.
at the beginning ofself.class.class_bang
in the instance methodinstance_bang
. It is not needed, because if no receiver is given,self
is assumed. If you're unsure, try it withclass.class_bang
. in IRB or PRY.self.class.class_bang
as it is. If you doclass.class_bang
, MRI sees it as aclass
keyword. So error you will be getting.self.
is needed to tell Ruby you are referring to the method, not the keyword, but why isn't Ruby smart enough to know that, considering thatclass
is chained toclass_bang
?self.
is needed, for example, when followed by a setter method, to distinguish it from a local variable, but I don't understand the need here, though this is probably not the place to dig into this.