P
Paul Smith
I've been toying with Ruby for a while, but only now am I beginning to
understand some of the amazing properties Ruby has. I was simply
floored when I realise you could add methods to an object dynamically.
So I saw this:
obj=Object.new
def obj.talk
puts "Hello!"
end
and was stunned. obj now has a talk method!
I took it to the next logical step, making a class which could add
methods to objects:
class FairyGodmother
def talkify(obj)
def obj.talk
puts "I'm a real boy!"
end
end
end
fairy = FairyGodother.new()
pinocchio = Object.new()
fairy.talkify(pinochio)
pinochio.talk # Success!
But my next logical leap doesn't work:
Changing the talkify method to this:
def talkify(obj, str)
def obj.talk
puts str
end
end
doesn't do what I mean - what it does is create a method called talk
which tries to output obj.str which doesn't exist. What I want is for
the obj.talk method to return the literal string given to the
fairy.talkify call.
How do I convince Ruby to evaluate str?
(Apologies if this is answered somewhere in The Well Grounded Rubyist
- I haven't finished the book yet )
understand some of the amazing properties Ruby has. I was simply
floored when I realise you could add methods to an object dynamically.
So I saw this:
obj=Object.new
def obj.talk
puts "Hello!"
end
and was stunned. obj now has a talk method!
I took it to the next logical step, making a class which could add
methods to objects:
class FairyGodmother
def talkify(obj)
def obj.talk
puts "I'm a real boy!"
end
end
end
fairy = FairyGodother.new()
pinocchio = Object.new()
fairy.talkify(pinochio)
pinochio.talk # Success!
But my next logical leap doesn't work:
Changing the talkify method to this:
def talkify(obj, str)
def obj.talk
puts str
end
end
doesn't do what I mean - what it does is create a method called talk
which tries to output obj.str which doesn't exist. What I want is for
the obj.talk method to return the literal string given to the
fairy.talkify call.
How do I convince Ruby to evaluate str?
(Apologies if this is answered somewhere in The Well Grounded Rubyist
- I haven't finished the book yet )