我希望能够动态命名方法(我不会将其留给用户输入来执行此操作,但作为示例):
puts ""
foo = gets
def (whatever the user inputted for foo)
end
我该怎么做?
最佳答案
您可以使用 send
方法向类发送消息,并使用参数 :define_method
告诉它您要为其定义一个新方法那个类(class)。
例如,有一个类 Car
class Car
end
c = Car.new
调用c.sound
会导致错误
NoMethodError: undefined method `sound' for #<Car:0x29d9048>
但是在定义方法名称并将其发送到类之后:
input = "sound"
Car.send(:define_method, input) do
puts "vroom!"
end
对 c.sound
的调用现在会带来输出
vroom!
关于ruby - 动态方法命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10358909/