Public and Private Methods in Ruby

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

This is a summary of the article:

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 methodsclass Person def name; end private def age; endend# Passing arguments to privateclass Person def age; end private :ageend# Passing method definition to privateclass Person private def age puts "I'm private" endend# Part 2/5: Protected methodsclass Employee protected def my_protected_method; endendclass Employee protected def my_protected_method; endendEmployee.new.my_protected_method # raises NoMethodErrorclass Director def call(employee) employee.my_protected_method endend# Part 3/5: Calling private or protected methodsclass Employee def my_public_method; end private end# using `send`# - will work for calling any method# - ⚠️ can be redefinedEmployee.new.send(:any_method) # using `public_send`# will only call public method, will not work on private or protectedEmployee.new.public_send(:my_public_method)# using `__send__`# - use this instead of `send`# - __send__ will show a warning when redefinedEmployee.new.__send__(:any_method)# Part 4/5: Private Class Methods# ❌ The following will NOT workclass Employee private def self.call; endend# ✅ This will work: class Employee class << self private def call; end endend# ✅ Or this will work:class Employee def self.call; end private_class_method :callend# ✅ This will also workclass Employee private_class_method def self.call; endend# Part 5/5: Constants and attributes# As they are defined in the class# Constants## ❌ The following will NOT workclass Employee private MY_CONSTANT = 1end## ✅ This will workclass Employee MY_CONSTANT = 1 private_constant :MY_CONSTANTend# You can define attr_accessor as private## Only from Ruby 3+class Employee private attr_accessor :name, :ageend

Reply

or to participate.