Skip to content

Instantly share code, notes, and snippets.

@zgfif
Last active December 28, 2018 21:14
Show Gist options
  • Save zgfif/6e74586430150072c54fb1ee31fe9af0 to your computer and use it in GitHub Desktop.
Save zgfif/6e74586430150072c54fb1ee31fe9af0 to your computer and use it in GitHub Desktop.
module ActsAsWalker
attr_reader :distance
def walk!
@distance += 1
end
end
module ActsAsSpeaker
attr_reader :speak, :gills
end
class Animal
attr_reader :name, :age
def initialize name:
@name = name
@age = 0
end
def birthday!
@age += 1
end
def can_swim?
@swim
end
def can_fly?
@fly
end
def has_milk?
@milk
end
end
class Fish < Animal
include ActsAsSpeaker
def initialize name:
super
@swim = true
@fly = false
@milk = false
@gills = 'yes'
end
def speak
raise NoMethodError
end
end
class Bird < Animal
include ActsAsWalker
include ActsAsSpeaker
def initialize name:
super
@swim = false
@fly = true
@milk = false
@speak = 'car'
@distance = 0
end
def gills
raise NoMethodError
end
end
class Mammal < Animal
include ActsAsWalker
include ActsAsSpeaker
def initialize name:
super
@swim = false
@fly = false
@milk = true
@speak = 'mo-o-o-o'
@distance = 0
end
def gills
raise NoMethodError
end
end
# Fish
fish = Fish.new name: 'Salmon'
p fish.name
p fish.age
fish.birthday!
p fish.age
p fish.can_swim?
p fish.can_fly?
p fish.has_milk?
# p fish.distance #NoMethodError
# p fish.walk! #NoMethodError
# p fish.speak #NoMethodError
p fish.gills
#Bird
bird = Bird.new name: 'Crow'
p bird.name
p bird.age
bird.birthday!
p bird.age
p bird.can_swim?
p bird.can_fly?
p bird.has_milk?
p bird.distance
bird.walk!
p bird.distance
p bird.speak
# p bird.gills #NoMethodError
#Mammal
mammal = Mammal.new name: 'Cow'
p mammal.name
p mammal.age
mammal.birthday!
p mammal.age
p mammal.can_swim?
p mammal.can_fly?
p mammal.has_milk?
p mammal.distance
mammal.walk!
p mammal.distance
p mammal.speak
# p mammal.gills #NoMethodError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment