Passing a method as a parameter in Ruby

2020-01-27 10:00发布

I am trying to mess around a little bit with Ruby. Therefor I try to implement the algorithms (given in Python) from the book "Programming Collective Intelligence" Ruby.

In chapter 8 the author passes a method a as parameter. This seems to work in Python but not in Ruby.

I have here the method

def gaussian(dist, sigma=10.0)
  foo
end

and want to call this with another method

def weightedknn(data, vec1, k = 5, weightf = gaussian)
  foo
  weight = weightf(dist)
  foo
end

All I got is an error

ArgumentError: wrong number of arguments (0 for 1)

8条回答
祖国的老花朵
2楼-- · 2020-01-27 10:35

The normal Ruby way to do this is to use a block.

So it would be something like:

def weightedknn( data, vec1, k = 5 )
  foo
  weight = yield( dist )
  foo
end

And used like:

weightenknn( data, vec1 ) { |dist| gaussian( dist ) }

This pattern is used extensively in Ruby.

查看更多
走好不送
3楼-- · 2020-01-27 10:36

you also can use "eval", and pass the method as a string argument, and then simply eval it in the other method.

查看更多
登录 后发表回答