Created
May 16, 2012 18:01
-
-
Save ivanacostarubio/2712657 to your computer and use it in GitHub Desktop.
How to implement polymorphic behavior
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 Animal | |
| def initialize | |
| end | |
| def talk | |
| raise NotImplementedError("Subclass must implement abstract method") | |
| end | |
| end | |
| class Cat | |
| def talk | |
| return 'Meow!' | |
| end | |
| end | |
| class Dog | |
| def talk | |
| return 'Woof! Woof!' | |
| end | |
| end | |
| animals = [Cat.new, | |
| Dog.new] | |
| animals.each do |animal| | |
| puts animal.talk() | |
| end | |
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 Animal | |
| attr_accessor :type | |
| def initialize | |
| end | |
| def talk | |
| if type == "Cat" | |
| return "Meow!" | |
| elsif type "Dog" | |
| return "Woof! Woof!" | |
| else | |
| return "WTF dude!" | |
| end | |
| end | |
| end |
Author
por que 4 espacios de indent?
Author
caring about indentation misses the point of the gist. ![]()
hurts my eyes.... ![]()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hablar como esto viola el Open Close Principle