Created
May 8, 2011 19:50
-
-
Save johncrisostomo/961636 to your computer and use it in GitHub Desktop.
RubyLearning Week4 - Optional Exercise 1
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 Dog | |
def initialize(name) | |
@name = name | |
end | |
def method_missing(name, *args, &block) | |
command = /(command)_(\w+)/.match(name) | |
if command | |
puts "#{@name} doesn't know to #{command[2]}!" | |
else | |
raise "It's not a valid trick" | |
end | |
end | |
def teach_trick(name, &block) | |
meth_name = 'command_' + name.to_s | |
define_singleton_method(meth_name.to_sym, &block) | |
end | |
end | |
d = Dog.new('Lassie') | |
d.teach_trick(:dance) { "#{@name} is dancing!" } | |
puts d.command_dance | |
d.teach_trick(:poo) { "#{@name} is a smelly doggy!" } | |
puts d.command_poo | |
puts | |
d2=Dog.new('Fido') | |
puts d2.command_dance | |
d2.teach_trick(:laugh) { "#{@name} finds this hilarious!" } | |
puts d2.command_laugh | |
puts d.command_laugh | |
puts | |
d3=Dog.new('Stimpy') | |
puts d3.command_dance | |
puts d3.command_laugh | |
puts d4.sample |
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
#teach_trick method only : | |
def teach_trick(name, &block) | |
singleton = class << self; self end | |
singeton.send(:define_method, name, &block) | |
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
class Dog | |
def initialize(name) | |
@name = name | |
end | |
def method_missing(name, *args, &block) | |
print "#{@name} doesn't know how to #{name}" | |
end | |
def teach_trick(name, &block) | |
define_singleton_method(name, &block) | |
end | |
end | |
d = Dog.new('Lassie') | |
d.teach_trick(:dance) { "#{@name} is dancing!" } | |
puts d.dance | |
d.teach_trick(:poo) { "#{@name} is a smelly doggy!" } | |
puts d.poo | |
puts | |
d2=Dog.new('Fido') | |
puts d2.dance | |
d2.teach_trick(:laugh) { "#{@name} finds this hilarious!" } | |
puts d2.laugh | |
puts d.laugh | |
puts | |
d3=Dog.new('Stimpy') | |
puts d3.dance | |
puts d3.laugh |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment