Skip to content

Instantly share code, notes, and snippets.

@kadru
Created October 19, 2018 02:01
Show Gist options
  • Save kadru/ddab0bf3d3d719e314553725d3d536d1 to your computer and use it in GitHub Desktop.
Save kadru/ddab0bf3d3d719e314553725d3d536d1 to your computer and use it in GitHub Desktop.
Explain ruby protected, private and public methods
#dwarf.rb
class Dwarf
include Comparable
def initialize(name, age, beard_strength)
@name = name
@age = age
@beard_strength = beard_strength
end
attr_reader :name, :age, :beard_strength
public :name
private :age
protected :beard_strength
# Comparable module will use this comparison method for >, <, ==, etc.
def <=>(other_dwarf)
# One dwarf is allowed to call this method on another
beard_strength <=> other_dwarf.beard_strength
end
def greet
"Lo, I am #{name}, and have mined these #{age} years.\
My beard is #{beard_strength} strong!"
end
def blurt
# Not allowed to do this: private methods can't have an explicit receiver
"My age is #{self.age}!"
end
end
#to launch interactive ruby at moment to execute this file
require 'irb'; IRB.start
gloin = Dwarf.new('Gloin', 253, 7)
gimli = Dwarf.new('Gimli', 62, 9)
gloin > gimli # false
gimli > gloin # true
gimli.name # 'Gimli'
gimli.age # NoMethodError: private method `age'
called for #<Dwarf:0x007ff552140128>
gimli.beard_strength # NoMethodError: protected method `beard_strength'
called for #<Dwarf:0x007ff552140128>
gimli.greet # "Lo, I am Gimli, and have mined these 62 years.\
My beard is 9 strong!"
gimli.blurt # private method `age' called for #<Dwarf:0x007ff552140128>
@kadru
Copy link
Author

kadru commented Oct 19, 2018

if a method is protected in Ruby, then it can be called implicitly by both the defining class and its subclasses. Additionally they can also be called by an explicit receiver as long as the receiver is self or of same class as that of self

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment