So I have some code which adds a method to a class based on user input
like
this:
class Klass
Do nowt originally
end
Get the name of a method to add
puts “Enter the name of the method to add”
$stdout.flush
methodName = gets
methodName.chomp!
puts “Adding method #{methodName}”
$stdout.flush
Add a method called ‘methodName’ to Klass
Klass.class_eval do
define_method(methodName) do |*values|
puts “Welcome to #{methodName}!”
puts values.to_s
end
end
Try to invoke the new method
instance = Klass.new
instance.send(methodName, “—”, “+++”)
List the methods of Klass
Klass.methods.sort.each do |method|
puts “Klass##{methodName}”
end
So, the code appears to work fine, in that the send() method is able to
call
the newly created method. So, does anyone know why is it when I list the
methods of the class Klass afterwards, the new method does not appear?
Also, is it possible to use define_method() to add class methods to
classes,
rather than just instance methods? I can’t seem to get it to work.
Regards,
Martin