ruby pass method as a parameter

Im trying to pass a method as a parameter to method_2, execute this one and return the result:

def method_2( method_p, param )
  res = method(method_p).call(param)
  return res
end

def method_1
  klass = MyKlass.instance
  return method_2( klass.foo, "test" )
end

this's MyKlass file:

class MyKlass
  def foo(param)
    param+param
  end
end

All I got is an error

wrong number of arguments (0 for 1)

Answers


You can use symbols to refer to methods:

def method_2(method_symbol, *args)
  send method_symbol, *args
end

However, since you're calling the method on a specific object, you would either have to pass that in as an additional argument, or use a proc or a lambda, which is like a block wrapped in an object:

def method_2(proc, *args)
  proc.call(*args)
end

method_2(->(param){ klass.foo(param) }, "test")

It's more common to just use blocks to do this:

def method_2(receiver, *args, &block)
  yield receiver, *args
end

method_2(klass, "test") do |receiver, param|
  receiver.foo(param)
end

All of these are fairly contrived examples; is there a specific problem you're trying to solve?


When you:

return method_2( klass.foo, "test" )

klass.foo requires one arg, that might be what's causing your error.


Need Your Help

Displaying divs inside container in dynamic number of rows

jquery html css

I want to display divs in rows. User chooses number of divs and then I want to display them in rows which number depends on number of divs. For example if user picked 6 I want to have 2 rows with 3...