Ruby:如何使用“发送”调用方法方法,带有哈希值?
假设我有一个 A 类,其中有一些方法。
可以说 string methodName 是这些方法之一,并且我已经知道要为其提供哪些参数。它们位于哈希 {'param1' =>; value1, 'param2' =>; value2}
所以我有:
params = {'param1' => value1, 'param2' => value2}
a = A.new()
a.send(methodName, value1, value 2) # call method name with both params
我希望能够通过传递我的哈希值来调用该方法。这可能吗?
Let say I have class A with some methods in it.
Lets say string methodName is one of those methods, and I already know what parameters I want to give it. They are in a hash {'param1' => value1, 'param2' => value2}
So I have:
params = {'param1' => value1, 'param2' => value2}
a = A.new()
a.send(methodName, value1, value 2) # call method name with both params
I want to be able to somehow call that method by passing my hash. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保 methodName 是一个符号,而不是一个字符串(例如 methodName.to_sym)
无法将哈希传递到发送中,您需要一个数组,并且其中的键/值不是按特定顺序排列,而是按参数排列该方法需要如此,因此您需要一些合理的方法来以正确的顺序获取值。
然后,我认为您需要使用 splat 运算符 (*) 传入该数组进行发送。
类似的事情。
Make sure the methodName is a symbol, not a string (e.g. methodName.to_sym)
Can't pass a hash into a send, you need an array, and the keys/values in it are not in a specific order, but the arguments to the method need to be, so you need some sensible way to get the values in the correct order.
Then, I think you need to use the splat operator (*) to pass in that array to send.
Something like that.
我目前使用的是 Ruby 2.2.2,您可以使用关键字机制传递哈希值和发送:
I am currently using Ruby 2.2.2 and you can pass in a hash along with send by using the keywords mechanic: