Skip to content

Instantly share code, notes, and snippets.

@duckinator
Created December 9, 2014 05:06
Show Gist options
  • Save duckinator/cdc64838eadb849f38f6 to your computer and use it in GitHub Desktop.
Save duckinator/cdc64838eadb849f38f6 to your computer and use it in GitHub Desktop.
Duck typing, explained with Ducks.
# 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.
~$ 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