Passing a method as a parameter in Ruby Passing a method as a parameter in Ruby ruby ruby

Passing a method as a parameter in Ruby


The comments referring to blocks and Procs are correct in that they are more usual in Ruby. But you can pass a method if you want. You call method to get the method and .call to call it:

def weightedknn( data, vec1, k = 5, weightf = method(:gaussian) )  ...  weight = weightf.call( dist )  ...end


You want a proc object:

gaussian = Proc.new do |dist, *args|  sigma = args.first || 10.0  ...enddef weightedknn(data, vec1, k = 5, weightf = gaussian)  ...  weight = weightf.call(dist)  ...end

Just note that you can't set a default argument in a block declaration like that. So you need to use a splat and setup the default in the proc code itself.


Or, depending on your scope of all this, it may be easier to pass in a method name instead.

def weightedknn(data, vec1, k = 5, weightf = :gaussian)  ...  weight = self.send(weightf)  ...end

In this case you are just calling a method that is defined on an object rather than passing in a complete chunk of code. Depending on how you structure this you may need replace self.send with object_that_has_the_these_math_methods.send


Last but not least, you can hang a block off the method.

def weightedknn(data, vec1, k = 5)  ...  weight =     if block_given?      yield(dist)    else      gaussian.call(dist)    end  end  ...endweightedknn(foo, bar) do |dist|  # square the dist  dist * distend

But it sounds like you would like more reusable chunks of code here.


You can pass a method as parameter with method(:function) way. Below is a very simple example:

def double(a)  return a * 2 end=> nildef method_with_function_as_param( callback, number)   callback.call(number) end => nilmethod_with_function_as_param( method(:double) , 10 ) => 20