On Mon, Jun 14, 2010 at 7:23 AM, Sateesh K.
[email protected] wrote:
I’m not sure if I understand you correctly, but if you want those
irb(main):008:1> end
Thanks for reply
flowerlist=Flower.new #----->Creating instance for flower
i think u understand my question
As I understand the question now, I think the answer from Phrogz is
spot on. You need to use the method_missing method, which will catch
any call to a method you haven’t defined:
class Flower
def jasmine
puts “iam jasmine”
end
def rose
puts “iam rose”
end
def method_missing meth, *args, &blk
puts “method #{meth} called, but not defined”
end
end
flowerlist=Flower.new #----->Creating instance for flower
flowerlist.jasmine #------->"gives output as “iam jasmine”
flowerlist.rose # =======> "gives output as “i am rose”
flowerlist.lotus #=> “method lotus called, but not defined”
So, now you know where you have a place to do whatever you want to do
with a call to a method that doesn’t exist. For example, if you want
to dynamically create a method that returns its name as a string, you
can do:
def method_missing method, *args, &blk
self.class.send(:define_method, method) do
method.to_s
end
send(method)
end
This will dynamically define (and call) a method that returns its name
as a string. So if you add that to the Flower class:
class Flower
def method_missing method, *args, &blk
self.class.send(:define_method, method) do
method.to_s
end
send(method)
end
end
f = Flower.new
f.lotus #=> “lotus”
f.rose #=> “rose”
and so on. In any case, I recommend looking at Phrogz’s answer,
because it’s a nice little utility to automatically define method that
do different things depending the the name patterns.
Regards,
Jesus.