Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Last active December 27, 2017 23:07
Show Gist options
  • Save onelharrison/e917ec203242054f5a99306afb586be8 to your computer and use it in GitHub Desktop.
Save onelharrison/e917ec203242054f5a99306afb586be8 to your computer and use it in GitHub Desktop.
Code snippets showing how to define public and private instance and class methods in Ruby.
class Car
attr_reader :mileage
def initialize
@mileage = 0
end
def drive
update_mileage
end
private
def update_mileage
@mileage += 1
end
end
# => car = Car.new
# #<Car:0x005..>
#
# => car.drive
# 1
#
# => car.update_mileage
# private method `update_mileage' called for #<Car:0x005..>
#
# => car.mileage
# 1
class Toyota < Car
def self.name
"Toyota #{superclass}"
end
end
# => Toyota.name
# "Toyota Car"
class Toyota < Car
class << self
def name
"Toyota #{superclass}"
end
end
end
# => Toyota.name
# "Toyota Car"
class Toyota < Car
def self.name
self.i_am
end
private
def self.i_am
"Toyota #{superclass}"
end
end
# => Toyota.name
# "Toyota Car"
# => Toyota.i_am # expecting an error
# "Toyota Car"
class Toyota < Car
class << self
def name
i_am
end
private
def i_am
"Toyota #{superclass}"
end
end
end
# => Toyota.name
# "Toyota Car"
#
# => Toyota.i_am # expecting an error
# private method `i_am' called for Toyota:Class
class Toyota < Car
def self.name
self.i_am
end
private_class_method def self.i_am
"Toyota #{superclass}"
end
end
# => Toyota.name
# "Toyota Car"
#
# => Toyota.i_am # expecting an error
# private method `i_am' called for Toyota:Class
class Toyota < Car
def self.name
self.i_am
end
def self.i_am
"Toyota #{superclass}"
end
def self.do_something
# I want to be private too
puts "I'm private too! I do something."
end
# I added do_something to show that
# private_class_method takes an array
# of symbols corresponding to method
# names.
private_class_method :i_am, :do_something
end
# => Toyota.name
# "Toyota Car"
#
# => Toyota.i_am # expecting an error
# private method `i_am' called for Toyota:Class
#
# => Toyota.do_something # expecting an error
# private method `do_something' called for Toyota:Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment