Created
December 9, 2014 05:06
-
-
Save duckinator/cdc64838eadb849f38f6 to your computer and use it in GitHub Desktop.
Duck typing, explained with Ducks.
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
# This is a Duck. It is clearly not a string. | |
class Duck | |
def to_s | |
" _ \n" + | |
"__(.)<\n" + | |
"\\___) \n" | |
end | |
end | |
# This displays Strings. It will clearly never display a Duck. | |
def print_if_string(x) | |
unless x.is_a?(String) | |
puts "A #{x.class} is not a String." | |
return | |
end | |
puts x | |
end | |
print_if_string(1) #=> "A Fixnum is not a String." | |
print_if_string("This is definitely a String") #=> "This is definitely a String." | |
print_if_string(Duck.new) #=> "A Duck is not a String" | |
class Duck | |
def is_a?(other) | |
super(other) || other == String | |
end | |
end | |
print_if_string(Duck.new) #=> A duck. |
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
~$ ruby ./duck-typing.rb | |
A Fixnum is not a String. | |
This is definitely a String | |
A Duck is not a String. | |
_ | |
__(.)< | |
\___) | |
~$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment