0
0
RubyHow-ToBeginner · 3 min read

How to Use Private Method in Ruby: Syntax and Examples

In Ruby, you define a private method inside a class by placing it below the private keyword. Private methods can only be called within the class and cannot be accessed with an explicit receiver like self.
📐

Syntax

To create a private method in Ruby, write the private keyword followed by method definitions. All methods defined after private become private until another visibility keyword is used.

  • private: keyword to mark methods as private
  • method_name: the name of the private method
  • Private methods cannot be called with an explicit receiver (like self.method_name)
ruby
class MyClass
  def public_method
    private_method
  end

  private

  def private_method
    puts "This is private"
  end
end
💻

Example

This example shows a class with a public method calling a private method internally. Trying to call the private method from outside the class will cause an error.

ruby
class Person
  def greet
    say_hello
  end

  private

  def say_hello
    puts "Hello!"
  end
end

person = Person.new
person.greet
# person.say_hello # This line would cause an error if uncommented
Output
Hello!
⚠️

Common Pitfalls

Common mistakes include trying to call private methods with an explicit receiver or from outside the class, which raises a NoMethodError. Also, placing private after method definitions does not make those methods private.

ruby
class Example
  private
  def secret
    puts "Secret method"
  end
end

ex = Example.new
# ex.secret # Raises NoMethodError: private method `secret' called for #<Example:0x0000>

class Example2
  def open
    puts "Open method"
  end
  private
  def hidden
    puts "Hidden method"
  end
end

ex2 = Example2.new
ex2.open
# ex2.hidden # Raises NoMethodError
Output
Open method
📊

Quick Reference

KeywordEffectUsage
privateMakes following methods privatePlace before method definitions
private methodsCannot be called with explicit receiverCalled only inside class without receiver
NoMethodErrorRaised if private method called externallyAvoid calling private methods outside class

Key Takeaways

Use the private keyword to mark methods as private inside a class.
Private methods can only be called without an explicit receiver inside the class.
Calling private methods from outside the class causes a NoMethodError.
Place private before method definitions to make them private.
Public methods can call private methods internally to hide implementation details.