tags:

views:

30

answers:

1

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?

A: 

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.

Andrew Kuklewicz
i need to sort inside my method, or sort the array?
dfgdfgd
What's wrong with "sending" a string instead of a symbol?
jordinl
I guess strings work too I had remembered that it should be a symbol, but I must be thinking of something else.
Andrew Kuklewicz
You need to sort the params values (see my example code), otherwise you don't know what order they will come out of the hash. If you just did params.values for example, their order is not predictable.
Andrew Kuklewicz