如何将参数传递给define_method?

时间:2020-03-06 14:19:49  来源:igfitidea点击:

我想将参数传递给使用define_method定义的方法,我该怎么做?

解决方案

我们传递给define_method的块可以包含一些参数。这就是我们定义的方法接受参数的方式。当我们定义一个方法时,我们实际上只是在给该块起个昵称并在类中保留对其的引用。参数随块一起提供。所以:

define_method(:say_hi) { |other| puts "Hi, " + other }

除了凯文·康纳(Kevin Conner)的回答:块参数不支持与方法参数相同的语义。我们不能定义默认参数或者块参数。

仅在Ruby 1.9中使用新的" stabby lambda"语法(支持完整的方法参数语义)修复了该问题。

例子:

# Works
def meth(default = :foo, *splat, &block) puts 'Bar'; end

# Doesn't work
define_method :meth { |default = :foo, *splat, &block| puts 'Bar' }

# This works in Ruby 1.9 (modulo typos, I don't actually have it installed)
define_method :meth, ->(default = :foo, *splat, &block) { puts 'Bar' }