Ruby中的字符串作为对象方法
可以使用字符串调用对象上的方法吗。例如,使用字符串Ruby中的字符串作为对象方法,ruby,Ruby,可以使用字符串调用对象上的方法吗。例如,使用字符串foo='bar',我如何在类Baz上调用bar:Baz.bar。另一种方法是创建这样的案例陈述 case foo when 'bar' Baz.bar when 'qux' Baz.qux end 您可以使用send对对象调用任何方法: foo = 'bar' Baz.send(foo) // calls bar on Baz foo = 'bar' Baz.public_send(foo) // calls only public
foo='bar'
,我如何在类Baz
上调用bar
:Baz.bar
。另一种方法是创建这样的案例陈述
case foo
when 'bar'
Baz.bar
when 'qux'
Baz.qux
end
您可以使用
send
对对象调用任何方法:
foo = 'bar'
Baz.send(foo) // calls bar on Baz
foo = 'bar'
Baz.public_send(foo) // calls only public method bar on Baz
这也会调用私有方法。如果只想调用公共方法,请使用public\u send
:
foo = 'bar'
Baz.send(foo) // calls bar on Baz
foo = 'bar'
Baz.public_send(foo) // calls only public method bar on Baz
如果要检查是否定义了公共方法,可以使用respond\u to?
foo = 'bar'
if Baz.respond_to?(foo)
// only gets executed if public method bar is defined on Baz
Baz.send(foo) // executes bar on Baz
end
如果还要检查私有方法,则必须提供true
作为第二个参数:
Baz.respond_to?(foo, true)
非常感谢。我在谷歌上搜索了很长时间,但我不知道应该搜索什么:+1:Hi@mu太短了,我在谷歌上搜索了一段时间以找到解决方案,但建议的副本从未出现过。我认为它从未出现过,因为它将方法称为函数。我很感激答案是一样的,但希望这个问题能在将来为开发人员节省一些时间。或者更新重复问题,改为使用术语“方法”,尤其是在标题中,以便在搜索时出现。