如何评估/常量化字符串到方法,然后将参数传递给它
给出:
s = "foo_bar_path"
我如何评估或常量化 s,并将参数传递给它,例如我的最终结果相当于:
foo_bar_path(@myvar, @foobar)
我正在尝试 eval(s).send
但这似乎并不工作。而且 Constantize 似乎只适用于类?
Given:
s = "foo_bar_path"
How can I eval or constantize s, and pass arguments to it, such as my final result would be the equivalent of:
foo_bar_path(@myvar, @foobar)
I was trying eval(s).send
but that doesn't seem to work. And constantize seems to only work on Classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需使用
send
方法 (或public_send
根据您的需要)在适当的对象上:或者如果您想对自己调用方法:
文档中说“符号”,但
send
也很乐意获取字符串中的方法名称。You would just use the
send
method (orpublic_send
depending on your needs) on the appropriate object:or if you want to call a method on yourself:
The documentation says "symbol" but
send
is just as happy to get the method name in a string.另一种处理此类事情的方法(对于 OpenStruct 更好):
Another way to go about this sort of this sort of thing (better for OpenStruct):