Created
June 12, 2013 07:41
-
-
Save georgebonnr/5763488 to your computer and use it in GitHub Desktop.
Another learning exercise. Learning to metaprogram.
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
class Dog | |
def initialize(name) | |
@name = name | |
end | |
def method_missing(m, *args, &block) | |
puts "#{@name} doesn't know how to #{m} yet!" | |
end | |
def eigenclass | |
class << self; self; end | |
end | |
def teach_trick(symbol, &block) | |
eigenclass.send(:define_method, symbol, &block) | |
end | |
end | |
d = Dog.new('Dogface') | |
d.teach_trick(:dance) { "#{@name} is dancing!" } | |
puts | |
puts d.dance | |
d.teach_trick(:poo) { "#{@name} is a smelly doggy!" } | |
puts d.poo | |
puts | |
d2=Dog.new('Muttbutt') | |
puts d2.dance | |
d2.teach_trick(:laugh) { "#{@name} finds this hilarious!" } | |
puts d2.laugh | |
puts d.laugh | |
puts | |
d3=Dog.new('Tre') | |
puts d3.dance | |
puts d3.laugh |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment