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"

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Creating a Menu Using Voice Control in Python integrating different technologies.

Simple shopping cart in Rails

Hello to myself!

Create a basic web application with Flask

Xerox Understood the Game Has Changed and Here Is Why.

Terraform and Ansible: Deploying a Multi-Region Architecture.

Using Expand Query in Power Automate with Dataverse | Dynamics 365

Our Unity Extension: Ultimate PlayerPrefs

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
Oscar Romero

Oscar Romero

More from Medium

Using .split in Ruby to transform strings into arrays

Computer code on a computer screen

Introduction of Node.JS

Backend story: coding a RestAPI in Ruby on Rails

Singleton Pattern in Ruby