Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中的字符串作为对象方法_Ruby - Fatal编程技术网

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太短了,我在谷歌上搜索了一段时间以找到解决方案,但建议的副本从未出现过。我认为它从未出现过,因为它将方法称为函数。我很感激答案是一样的,但希望这个问题能在将来为开发人员节省一些时间。或者更新重复问题,改为使用术语“方法”,尤其是在标题中,以便在搜索时出现。