Short Ruby Newsletter

Share this post

Public and Private Methods in Ruby

newsletter.shortruby.com
Code Summaries

Public and Private Methods in Ruby

#ruby #code #private #public #methods #class #codesample

Lucian Ghinda
Aug 31, 2022
2
Share this post

Public and Private Methods in Ruby

newsletter.shortruby.com

This is a summary of the article:

https://paweldabrowski.com/articles/public-private-and-protected-in-ruby

with some ideas from the discussions on Reddit


Here is the code if you want to copy/paste it:


# Part 1/5: Common way of defining private methods

class Person
  def name; end

  private  
  def age; end
end

# Passing arguments to private
class Person
  def age; end
  private :age
end

# Passing method definition to private
class Person
  private def age 
    puts "I'm private"
  end
end

# Part 2/5: Protected methods

class Employee
  protected

  def my_protected_method; end
end

class Employee
  protected def my_protected_method; end
end

Employee.new.my_protected_method # raises NoMethodError

class Director
  def call(employee)
    employee.my_protected_method
  end
end

# Part 3/5: Calling private or protected methods
class Employee
  def my_public_method; end
  private 
end

# using `send`
# - will work for calling any method
# - ⚠️ can be redefined
Employee.new.send(:any_method) 

# using `public_send`
# will only call public method, will not work on private or protected
Employee.new.public_send(:my_public_method)

# using `__send__`
# - use this instead of `send`
# - __send__ will show a warning when redefined
Employee.new.__send__(:any_method)

# Part 4/5: Private Class Methods

# ❌ The following will NOT work
class Employee
  private

  def self.call; end
end

# ✅ This will work: 
class Employee
  class << self
    private

    def call; end
  end
end

# ✅ Or this will work:
class Employee
  def self.call; end
  private_class_method :call
end

# ✅ This will also work
class Employee
  private_class_method def self.call; end
end


# Part 5/5: Constants and attributes
# As they are defined in the class

# Constants
## ❌ The following will NOT work
class Employee
  private

  MY_CONSTANT = 1
end

## ✅ This will work
class Employee
  MY_CONSTANT = 1
  private_constant :MY_CONSTANT
end

# You can define attr_accessor as private
## Only from Ruby 3+
class Employee
  private attr_accessor :name, :age
end

Share this post

Public and Private Methods in Ruby

newsletter.shortruby.com
Previous
Next
Comments
TopNewCommunity

No posts

Ready for more?

© 2023 Lucian Ghinda
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing