You want a proc object:
gaussian = Proc.new do |dist, *args| sigma = args.first || 10.0 ... end def weightedknn(data, vec1, k = 5, weightf = gaussian) ... weight = weightf.call(dist) ... end
Just remember that you cannot set a default argument in a block declaration. Therefore, you need to use splat and set the default value in the proc code itself.
Or, depending on your scope, it might be easier to pass in place of the method name.
def weightedknn(data, vec1, k = 5, weightf = :gaussian) ... weight = self.send(weightf) ... end
In this case, you simply call the method that is defined on the object, and not pass the complete code snippet. Depending on how you structure it, you may need to replace self.send with object_that_has_the_these_math_methods.send
Last but not least, you can hang a block using the method.
def weightedknn(data, vec1, k = 5) ... weight = if block_given? yield(dist) else gaussian.call(dist) end end ... end weightedknn(foo, bar) do |dist|
But it looks like you would like to use multiple code snippets here.
Alex Wayne Feb 07 '09 at 0:24 2009-02-07 00:24
source share