Method Access Control in Ruby

class Person
attr_accessor :name, :age
def initialize(name)
@name = name
@age = 20
end
def get_age
age
end
end
bob = Person.new('Bob')
bob.name
=> 'Bob'
bob.get_age
=> '20'
class Person
attr_accessor :name
attr_writer :age
def initialize(name)
@name = name
end
def get_age
age
end

private
attr_reader :age
end
bob = Person.new('Bob')
bob.age = 20
bob.age
=> NoMethodError (private method called...)
bob.get_age
=> 20
class Person
attr_accessor :name
attr_writer :age
def initialize(name)
@name = name
@age = 20
end
def ==(other)
age_compare = age == other.age
age_compare ? "same age" : "different age"
end
protected
attr_reader :age
end
bob = Person.new('Bob')
rob = Person.new('Rob')
rob.age = 10
cobb = Person.new('Cobb')
bob.age
=> NoMethodError (protected method...)
bob == rob
=> "different age"
bob == cobb
=> "same age"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store