动态方法命名

我希望能够动态命名方法(我不会把它留给用户输入来做这个,但作为一个例子):

puts "" foo = gets def (whatever the user inputted for foo) end 

我怎样才能做到这一点?

您可以使用send方法将消息发送到类,使用参数:define_method告诉它您将为该类定义一个新方法。

例如,有一个类Car

 class Car end c = Car.new 

调用c.sound会导致错误

 NoMethodError: undefined method `sound' for # 

但是在定义方法的名称并将其发送到类之后:

 input = "sound" Car.send(:define_method, input) do puts "vroom!" end 

c.sound的调用现在带来了输出

 vroom! 

最常用的方法是: define_methodclass_evalinstance_eval 。 定义method_missing方法也使用了很多。

 #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以类似的方式使用,但在类的实例上定义。 define_method也类似:

 #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! 

搜索“Ruby Metaprogramming”,那里有很多教程。