Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dynamic

ruby

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?

like image 317
dfgdfgd Avatar asked Sep 10 '10 18:09

dfgdfgd


2 Answers

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.

like image 100
Andrew Kuklewicz Avatar answered Sep 23 '22 19:09

Andrew Kuklewicz


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)
like image 25
danteyxw Avatar answered Sep 24 '22 19:09

danteyxw