Created
August 28, 2017 15:00
-
-
Save buwilliams/e4f7588b5e7121bdb31bce584d245150 to your computer and use it in GitHub Desktop.
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 Dog | |
def speak | |
puts 'Ruff! Grr! Roof! Rawr!' | |
end | |
end | |
class Cat | |
def speak | |
puts 'Meeeow...' | |
end | |
end | |
class Bird | |
def speak | |
puts 'Tweety, tweet, tweet' | |
end | |
end | |
class AnimalShelter | |
attr_accessor :animals | |
def initialize | |
@animals = Array.new | |
end | |
def add(animal) | |
@animals << animal | |
end | |
def open_doors | |
animals.each do |animal| | |
animal.speak | |
end | |
end | |
end | |
animal_shelter = AnimalShelter.new | |
3.times { animal_shelter.add Cat.new } | |
2.times { animal_shelter.add Dog.new } | |
4.times { animal_shelter.add Bird.new } | |
animal_shelter.open_doors | |
# Explorations: | |
# 1. How might we sort/get data on animals without adding coupling to | |
# AnimalShelter? (interweave, specify order, 1 of each, count each) | |
# 2. How could we change the mechanism for output without changing all the | |
# animal classes? | |
# 3. How would the impl be different if we used Ruby's Enumerable for | |
# AnimalShelter? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a way to generalize speech. Move
speak
from each animal and place it inAnimal
superclass, then definespeech
for each animal with just a string.The interesting change here is the
speak
method implementation. First we've objectified the block (if any) in the argument list - the&
keyword turns a block into an object (specifically aproc
), or turns aproc
into a block.Then we've basically said "
block
is equal toblock
unless I didn't give you anything, in which case it's equal to a proc that contains aputs
statement".Basically you can give the speak method any writer you want in its block during runtime. You can definitely get fancier, but that's a basic start.