-
-
Save bendavis78/89afb5528edf14066431d4f980dd2590 to your computer and use it in GitHub Desktop.
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
class OriginPokemon | |
# Create a strength attribute that can be accessed on all instances | |
attr_accessor :strength | |
# `initialize` is our constructor method | |
def initialize | |
# Set strength to a default value of 100. | |
@strength = 100.0 | |
# We want all inheriting pokemon to have half the strength of its parent | |
# class (ie, its superclass). To do this we gather the entire class | |
# hierarchy into an array so that we can loop through it in reverse. | |
hierarchy = [] | |
# Get the class of the current instance. The built-in `self` variable points | |
# to the current instance, so we can use `self.class` to get the class of | |
# our current instance. For example, if we call `Pikachu.new`, a | |
# `self.class` will be Pikachu (even though this method is defined in the | |
# `Creator` class, `self` will point to the instance from the time the | |
# `.new` constructor was called). | |
my_type = self.class | |
# Get the parent class and save in a variable called `parent_type` | |
parent_class = my_type.superclass | |
# Add the type to our array and get the next superclass, until we hit the | |
# top of the hierarchy (when the superclass is Object) | |
while parent_class != Object | |
hierarchy.push(parent_class) | |
parent_class = parent_class.superclass | |
end | |
# Loop through the reversed hierarchy (top-down) and cut strength in half | |
hierarchy.reverse.each do |type| | |
puts "#{type} strength is #{@strength}" | |
@strength = @strength / 2 | |
end | |
puts "#{my_type} strength is #{@strength}" | |
end | |
end | |
# These other classes represent the hierarchy all the way down to Pikachu. We | |
# could, if we wanted, add more attributes and methods that are common to each | |
# class. | |
class Reptilia < OriginPokemon | |
end | |
class Mamallia < Reptilia | |
end | |
class Rodentia < Mamallia | |
end | |
class Pikachu < Rodentia | |
def fight | |
puts "Pikachu caused #{@strength} damage" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment