如何从字符串调用实例方法?
How do I call instance method from string?
假设我有一个 class
class MyClass
def sayMyName()
puts "I am unknown"
end
end
并且我已将此方法名称存储在一个变量中:methodName = "saymyName"
我想用上面的变量调用这个方法,像这样:
instance = MyClass.new
instance[methodName]
我知道可以使用宏调用它,但我不知道如何调用?请有人提供示例并进行解释。
更新 1
已经有一个答案:
但这并没有回答当方法在 class.
中时如何做
我已经修改了更新中给出的示例:
class Foo
def method1
puts "i'm method1"
end
def method2
puts "i'm method2"
end
def method3
puts "i'm method3"
end
def bar
{ "ctrl": -> { method1 },
"shift": -> { method2 },
"alt": -> { method3 }
}
end
def [](method)
bar[method]
end
end
binding = ["ctrl", "shift", "alt"].sample
foo = Foo.new
foo[binding].call #=> one of them
假设我有一个 class
class MyClass
def sayMyName()
puts "I am unknown"
end
end
并且我已将此方法名称存储在一个变量中:methodName = "saymyName"
我想用上面的变量调用这个方法,像这样:
instance = MyClass.new
instance[methodName]
我知道可以使用宏调用它,但我不知道如何调用?请有人提供示例并进行解释。
更新 1
已经有一个答案:
我已经修改了更新中给出的示例:
class Foo
def method1
puts "i'm method1"
end
def method2
puts "i'm method2"
end
def method3
puts "i'm method3"
end
def bar
{ "ctrl": -> { method1 },
"shift": -> { method2 },
"alt": -> { method3 }
}
end
def [](method)
bar[method]
end
end
binding = ["ctrl", "shift", "alt"].sample
foo = Foo.new
foo[binding].call #=> one of them