Created
December 14, 2018 18:05
-
-
Save joemsak/b09dbbc61ddc2e4ff75107d85c65893d to your computer and use it in GitHub Desktop.
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 Drink | |
def sip | |
puts "You drank with caution" | |
end | |
end | |
class Coffee < Drink | |
def method_missing(method_name, *args, &block) | |
if method_name == :gulp | |
puts "Please don't gulp your coffee!" | |
sip | |
else | |
super | |
# this will do the normal thing of raising an exception that the method wasn't found | |
end | |
end | |
end | |
class Water < Drink | |
def gulp | |
puts "You drank the water with reckless abandon!" | |
end | |
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
# Output: | |
> coffee = Coffee.new | |
=> #<Coffee:0x00007ffd5509ac18> | |
irb(main):039:0> coffee.gulp | |
Please don't gulp your coffee! | |
You drank with caution | |
=> nil | |
> coffee.eat | |
Traceback (most recent call last): | |
3: from /Users/joemsak/.asdf/installs/ruby/2.5.1/bin/irb:11:in `<main>' | |
2: from (irb):40 | |
1: from (irb):32:in `method_missing' | |
NoMethodError (undefined method `eat' for #<Coffee:0x00007ffd5509ac18>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment