Ruby Basics : Hiding a Class Method
To learn how the private keyword differs when it is used to hide class methods.
class Foo def self.greet p 'hi' end end Foo.greet
This prints 'hi'.
class Foo def self.greet p 'hi' end private def bar p 'bar' end end Foo.new.bar
NoMethodError: private method ‘bar’ called for #<Foo:0x00200>.
This is as expected.
class Foo def self.greet p 'hi' end private def self.gold p 'gold' end end Foo.gold
This is a surprise because it prints gold. The private keyword does not prevent the gold from getting called outside of Foo class.
How do we hide a class method?
class Foo class << Foo private def gold p 'gold' end end end Foo.gold
Now we get:
NoMethodError: private method ‘gold’ called for Foo:Class
class Foo def self.greet gold end private class << Foo private def gold p 'gold' end end end Foo.greet
This prints 'gold'. So, you can use the public interface that calls the private class method. It will work.
You can also use privateclassmethod to make existing class methods private as suggested by Matt Brictson on rubyflow.com.
class Foo private_class_method :gold def self.gold p 'gold' end end Foo.gold
If you run this, you will see:
NameError: undefined method ‘gold’ for class `Class'
In this article, we saw how the private keyword does not hide class methods and what we can do if we need to hide them.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview