Ruby 为 return proc 定义使用参数的方法

Ruby define method to return proc which makes use of an argument

在 Ruby 中,我想定义一个带有参数的方法,returns 一个包含使用该参数的方法的过程。类似下面的内容

def test(word)
  proc do
    def hello
      puts word
    end
  end
end

my_proc = test('hello')
my_proc.call.hello

当运行这段代码时,局部变量'word'未定义

为了提供更多上下文,我正在尝试使用 association extensions,它允许您向关联提供方法块以在关联上定义额外的辅助方法。我有一些方法我想在几个具有相似关联的相似活动记录模型上使用,但它们在调用时仅在某个符号上有所不同(连接的名称 table 传递给 through has_many 关系)。所以理想情况下,我正在考虑制作一个接受该符号的方法,然后可以将其用于关联扩展的实现。

你的例子有两个问题:

  1. 你不能这样调用 "proc full of methods" -- 它会作为关联扩展工作,但块被评估为模块主体,而不是 called.

  2. def关键字重置局部变量作用域。要将值放入函数中,您可以使用 define_method 来定义它(该块保留周围的范围),或者将值放在函数能够找到它的其他地方(class 变量, 例如).


def test(word)
  proc do
    define_method(:hello) do
      puts word
    end
  end
end

Class.new(&test("hello")).new.hello

另外,如果您在多个关联上定义大致相同的方法,则可能有更简单的方法,将它们定义为 class 级范围。

这就像你的电话。

def test(word)
  proc do
    define_method :hello do
      puts word
    end
  end
end

my_proc = test('hello world')
my_proc.call.hello

广告 returns # => hello world

编辑: 获取 @engineersmnky 评论,之后您可以简单地调用 hello.

您可以在这里找到更多信息:Is it possible to have Methods inside Methods?