Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
# 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