Skip to content

Instantly share code, notes, and snippets.

@silverhammermba
Created August 31, 2012 03:09
Show Gist options
  • Save silverhammermba/3548473 to your computer and use it in GitHub Desktop.
Save silverhammermba/3548473 to your computer and use it in GitHub Desktop.
Ruby OOP example
class Person
def initialize name, dob
@name = name
@dob = dob
end
def age
(Time.now - @dob) / (365 * 24 * 60 * 60)
end
def introduce_yoself
print "Hey, I'm #{@name} and I was born #{age} years ago.\n"
end
end
maxxx = Person.new("Max", Time.new(1988, 9, 11))
maxxx.introduce_yoself
# which prints
# "Hey, I'm Max and I was born 23.986193869358075 years ago."
class CoolDude < Person
def initialize name, dob, nickname
super name, dob
@nickname = nickname
end
def introduce_yoself
print "Yo, they call me '#{@nickname}'."
end
end
waltr0x = CoolDude.new("Walter", Time.new(1987, 9, 29), "The Laser")
# we've still got this function
print waltr0x.age
# 24.939627905041938
waltr0x.introduce_yoself
# "Yo, they call me 'The Laser'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment