Thanks for reply
i would like to know which methods are called by class object i.e
class Flower
=A0 =A0 def jasmine
=A0 =A0 puts "iam jasmine"
=A0 end
=A0 =A0 =A0def rose
=A0 =A0 =A0puts "iam rose"
=A0end
end
flowerlist=3DFlower.new #----->Creating instance for flower
flowerlist.jasmine =A0#------->"gives output as "iam jasmine"
flowerlist.rose =A0# =3D=3D=3D=3D=3D=3D=3D> "gives output as "i am rose"
flowerlist.lotus =A0 #------->"Shows No Method Error"
Question : --> My Question is i would like to know which methods are
called by object i.e flowerlist =A0in the class Flower
if i already know those methods then
suppose if i have not define some method then i will define it
dynamically example here is "lotus"
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=3DFlower.new #----->Creating instance for flower
flowerlist.jasmine #------->"gives output as "iam jasmine"
flowerlist.rose # =3D=3D=3D=3D=3D=3D=3D> "gives output as "i am rose"
flowerlist.lotus #=3D> "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 =3D Flower.new
f.lotus #=3D> "lotus"
f.rose #=3D> "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.