RobertJoseph
RobertJoseph

Reputation: 8158

Passing a method as a parameter

Is there are way to pass a method as a parameter without using a Proc object or block? The answers I've seen to similar questions rely on creating a Proc object.

def call_a_method_via_a_parameter( &some_method )
  # ?? call some_method and pass it a parameter ??
end
def my_method( param )
  puts param
end

call_a_method_via_a_parameter( &:my_method )

Upvotes: 3

Views: 164

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369430

Ruby is an object-oriented language. You can only pass around and manipulate objects, but methods aren't objects, ergo, you cannot pass them around.

You can, however, ask Ruby to give you a proxy object for a method via the Object#method method, which will return a Method object (which duck-types Proc):

def call_a_method_via_a_parameter(some_method)
  some_method.('Hi')
end

def my_method(param)
  puts param
end

call_a_method_via_a_parameter(method(:my_method))
# Hi

An alternative would be to pass the name of the method as a Symbol:

def call_a_method_via_a_parameter(some_method)
  public_send(:some_method, 'Hi')
end

def my_method(param)
  puts param
end

call_a_method_via_a_parameter(:my_method)
# Hi

So, in short: no, you cannot pass the method, but you can pass either the name of the method or a proxy object for the method.

However, the idiomatic way would be to use a block:

def call_a_method_via_a_parameter
  yield 'Hi'
end

def my_method(param)
  puts param
end

call_a_method_via_a_parameter(&method(:my_method))
# Hi

Upvotes: 2

Michael Johnston
Michael Johnston

Reputation: 5320

def bob(jeff)
  puts "hi #{jeff}"
end

def mary(meth, params)
  meth.call(params)
end

mary(method(:bob), 'yo')
=> hi yo

Upvotes: 4

Related Questions