Created
October 19, 2018 02:01
-
-
Save kadru/ddab0bf3d3d719e314553725d3d536d1 to your computer and use it in GitHub Desktop.
Explain ruby protected, private and public methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
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
Private methods can be called only implicitly. They cannot be called by explicit receivers like an object or the keyword self. For the same reason, private methods cannot be called outside the hierarchy of the defining class.