Skip to content

Instantly share code, notes, and snippets.

@georgebonnr
Created June 12, 2013 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgebonnr/5763488 to your computer and use it in GitHub Desktop.
Save georgebonnr/5763488 to your computer and use it in GitHub Desktop.
Another learning exercise. Learning to metaprogram.
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