A few days ago Chad Fowler ran the following quick quiz on Twitter:
Ruby quiz: in 140 chrs or less, why doesn't this work: class Y; def a; self.x end; private; def x; puts "hi" end end; Y.new.a
Here is the formatted version:
class Y def a self.x end private def x puts "hi" end end Y.new.a
Running this produces the following error:
a.rb:3:in `a': private method `x' called for #<Y:0x7f819a82d548> (NoMethodError) from a.rb:11
I wasn't immediately able to figure out what was wrong with this code and since access control is one of those fundamental things that you should know, if you want to be a decent Ruby developer, I decided to dig a little further to figure it out. Here is the scoop.
Private, Protected and Public – Ruby Method Visibility
The concept of private, protected and public methods in Ruby is somewhat different than it is in languages like Java (well, not so much public, that's very similar :)). In Java if a method is declared private, it can only be accessed from other methods in the same class. When a method is declared protected it can be accessed by other classes in the same package as well as by subclasses of its class in a different package. When a method is public it is – of course – always visible to everyone. So, in essence with Java, these keywords protect the various members from access by classes, depending on where these classes are in the inheritance/package hierarchy.