Last active
October 25, 2017 21:05
-
-
Save gabriel-dehan/e7a78246675ae021e4348bb4a1be18c8 to your computer and use it in GitHub Desktop.
New idea/example for teaching inheritance, class methods and self in Ruby
This file contains hidden or 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
# -------------- INHERITANCE --------------- | |
class Building # < Object | |
def initialize(width, length) | |
@width = width | |
@length = length | |
end | |
# Inheritance example | |
def has_garden? | |
false | |
end | |
# Super example | |
def surface | |
@width * @length | |
end | |
# def to_s; end | |
end | |
class House < Building | |
def initialize(width, length, address, color) | |
super(width, length) # super example | |
@address = address | |
@color = color | |
end | |
# Inheritance override example | |
def has_garden? | |
true | |
end | |
# Super example | |
def surface | |
super + 15 # + garden | |
end | |
end | |
class Castle < Building | |
def initialize(width, length, address, butler) | |
super(width, length) # super example | |
@address = address | |
@butler = butler | |
end | |
# Inheritance override example | |
def has_garden? | |
true | |
end | |
# Super example | |
def surface | |
super + 80 # + big garden | |
end | |
end | |
class ContainerHouse < Building | |
# No difference with the initialize so we don't need it | |
# Inheritance override example | |
def has_garden? | |
"the world is my garden" # still true though ;) | |
end | |
end | |
# ----------------- SELF & CLASS METHODS ---------- | |
class City | |
attr_reader :buildings | |
def initialize(name) | |
@name = name | |
@buildings = [] | |
end | |
def add_building(building) | |
@buildings << building | |
end | |
def remove_building(building) | |
@buildings.delete(building) | |
end | |
def to_s | |
"#{@name} is a city grand of #{@buildings.length} majestuous buildings." | |
end | |
end | |
class ContainerHouse < Building | |
def self.build_in_city(city, width, length) | |
# Create new instance of house | |
new_house = ContainerHouse.new(width, length) | |
# new_house = self.new(width, length) | |
# Add the building to the city | |
city.add_building(new_house) | |
end | |
def move_to_city(city) | |
# Remove the building from the former city | |
@city.remove_building(self) | |
# Change the city | |
@city = city | |
# Add the building to the new city | |
city.add_building(self) | |
end | |
end | |
paris = City.new("Paris") | |
dresde = City.new("Dresde") | |
mobilom = ContainerHouse.build_in_city(paris, width, length) | |
p paris.buildings | |
p dresde.buildings | |
mobilom.move_to_city(dresde) | |
p paris.buildings | |
p dresde.buildings | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment