开发者

Ruby: How to call a method using the 'send' method, with a hash?

开发者 https://www.devze.com 2023-01-15 10:20 出处:网络
Let say I have class A with some methods开发者_JS百科 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\'

Let say I have class A with some methods开发者_JS百科 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?


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.

methodName = 'center'    
params = {'param1' => 20, 'param2' => '_'}.sort.collect{|k,v| v}
a = "This is a string"
a.send(methodName.to_sym, *params)

=> "__This is a string__"

Something like that.


I am currently using Ruby 2.2.2 and you can pass in a hash along with send by using the keywords mechanic:

params = {param1: value1, param2: value2}
a = A.new()
a.send(methodName, params)
0

精彩评论

暂无评论...
验证码 换一张
取 消