Skip to content

Instantly share code, notes, and snippets.

@alebaffa
Last active August 29, 2015 13:57
Show Gist options
  • Save alebaffa/9383372 to your computer and use it in GitHub Desktop.
Save alebaffa/9383372 to your computer and use it in GitHub Desktop.
class Dog
def initialize(name)
@name = name
end
def bark
'woof!'
end
def eat
'gnam gnam!'
end
def chase_cat
'arf arf arf!'
end
def teach_trick(name, &block)
self.class.send(:define_method, name, &block)
end
end
d = Dog.new('Lassie')
d.teach_trick(:dance) { "#{@name} is dancing!" }
puts d.dance #=> Lassie is dancing!
d.teach_trick(:poo) { "#{@name} is a smelly doggy!" }
puts d.poo #=> Lassie is a smelly doggy!
d2 = Dog.new('Fido')
puts d2.dance #=>Fido is dancing!
d2.teach_trick(:laugh) { "#{@name} finds this hilarious!" }
puts d2.laugh #=>Fido finds this hilarious!
puts d.laugh #=>Lassie finds this hilarious!
d3 = Dog.new('Stimpy')
puts d3.dance #=>Stimpy is dancing!
puts d3.laugh #=>Stimpy finds this hilarious!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment