Skip to content

Instantly share code, notes, and snippets.

@nthj
Created December 4, 2013 17:41
Show Gist options
  • Save nthj/7792072 to your computer and use it in GitHub Desktop.
Save nthj/7792072 to your computer and use it in GitHub Desktop.
Class vs Instance
class Car
class << self
def advertise(model)
puts "BUY IT NOW! #{model}"
end
def manufacture(make)
Car.new(make)
end
end
def initialize(make)
@make = make
end
def drive(miles)
puts "Driving #{miles} miles"
end
end
civic = Car.new('Civic')
civic.drive(30)
Car.manufacture('Ford')
Car.advertise('Tesla Model S')
class Expense
class << self
@@expenses = []
def itemize
@@expenses.sort.each do |record|
puts "* #{record.name}, #{record.amount}"
end
end
def submit(minimum_amount = 70)
@@expenses.each do |record|
record.submit if record.amount >= minimum_amount
end
end
end
attr_accessor :name, :amount
def initialize(name, amount)
@name = name
@amount = amount
@@expenses << self
end
def <=>(other)
other.amount <=> @amount
end
def submit
puts "Submitting #{name} for #{amount}"
end
end
gas = Expense.new('gas receipt', 70)
flight = Expense.new('southwest', 150)
hotel = Expense.new('a hilton', 100)
# Expense.itemize
Expense.submit(70)
class Person
@@room = []
class << self
def room
@@room
end
end
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
@@room << self
end
def greet(name)
# Hey, John, I'm Bob.
puts "Hey, #{name}! I'm #{@name} and I'm #{@age}."
end
# TODO: we have to have their birthday,
# not just their age
def days_until_birthday
42
end
def <=>(other)
other.age <=> @age
end
end
bob = Person.new('Bob', 82)
john = Person.new('John', 24)
puts "Bob's age: " + bob.age.to_s
puts bob.greet('John')
puts "There are #{Person.room.length} people in the room."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment