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

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

this's MyKlass file:

class MyKlass
  def foo(param)

All I got is an error

wrong number of arguments (0 for 1)


You can use symbols to refer to methods:

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

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)*args)

method_2(->(param){ }, "test")

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

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

method_2(klass, "test") do |receiver, param|

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

When you:

return method_2(, "test" ) 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...