Reputation: 1184
I want to be able to name methods dynamically (I would not leave it up to user input to do this, but as an example):
puts ""
foo = gets
def (whatever the user inputted for foo)
end
How can I do this?
Upvotes: 2
Views: 738
Reputation: 15284
The most commonly used approaches are: define_method
, class_eval
and instance_eval
. Define method_missing
method is also used a lot.
#An example of class_eval
class Foo
end
foo = gets.chomp
#suppose you input bar here
Foo.class_eval %Q{
def #{foo}
puts "This is #{foo} method you defined!"
end
}
Foo.new.bar
#output: This is the bar method you defined!
instance_eval
is used in a similar way but defined on a instance of a class.
define_method
is also similar:
#An example of define_method
klass = Class.new
foo = gets.chomp
#suppose you typed bar
klass.send(:define_method,foo) do
puts "This is #{foo} method you defined!"
end
klass.new.bar
#output: This is bar method you defined!
Search "Ruby Metaprogramming" and there are many tutorials out there.
Upvotes: 0
Reputation: 8657
You can do this using the send
method to send a message to the class, using the parameter :define_method
to tell it you are going to define a new method for that class.
For example, having a class Car
class Car
end
c = Car.new
A call to c.sound
brings about the error
NoMethodError: undefined method `sound' for #<Car:0x29d9048>
But after defining the name of the method and sending it to the class:
input = "sound"
Car.send(:define_method, input) do
puts "vroom!"
end
The call to c.sound
now brings the output
vroom!
Upvotes: 3