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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With