Created
August 31, 2012 03:09
-
-
Save silverhammermba/3548473 to your computer and use it in GitHub Desktop.
Ruby OOP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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