Access Control in Ruby
Ruby gives you three levels of access protection, public, protected and private. The public methods can be called by anyone. In this article, we will look at some examples to learn about the access control and the subtle difference between private and protected access control.
Internal Visibility
class Foo
def testing_public
end
protected
def testing_protected
end
private
def testing_private
end
def ok
testing_public
testing_protected
testing_private
end
end
f = Foo.new
f.ok
This will throw the exception.
NoMethodError: private method ‘ok’ called for Foo.
External Visibility
Only the public method can be called outside the Foo class.
f = Foo.new
f.testing_public
will work. The methods testing_protected and testing_private will not work.
Difference between Private and Protected
The difference between private and protected can be demonstrated using the example below. The Foo class remains the same as shown above.
class Bar < Foo
def do_something(parent)
parent.testing_public
parent.testing_protected
parent.testing_private
end
end
b = Bar.new
b.do_something(Foo.new)
We can call the protected method but we cannot call the private method. We will get the error:
NoMethodError: private method ‘testing_private’ called for Foo.
This article is based on the blog post by Aaron Patterson.
Related Articles