abdul ahmad abdul ahmad - 2 months ago 6
Ruby Question

Pass method name as parameter to another method

I want to pass a method name, not a block, as a parameter to another method to use as a callback:

def one(param)
puts param
end

def two(param, &callback)
callback.call(param)
end

two('hi', :one)


Is this possible? I tried it and got an error saying I passed two parameters but only one was expected.

Answer

You want to use send:

def two(param, callback)
  send(callback, param)
end