模块的未定义局部变量或方法

Undefined local variable or method for module

我的模块 CurrencyExchange 具有以下方法

 CURRENCIES = %w(uah rub eur usd)

 def available_currencies
   CURRENCIES.join(' ').downcase.split.permutation(2)
 end

当我想将 available_currencies

一起使用时

define_method

 available_currencies.each do |(c1, c2)|
    define_method(:"#{c1}_to_#{c2}") do |cr| ... end end

我有一个错误

undefined local variable or method `available_currencies'
 for CurrencyExchange:Module (NameError)

但是当我使用它时

     CURRENCIES.join(' ').downcase.split.permutation(2).each do |(c1, c2)|
  define_method(:"#{c1}_to_#{c2}") .... end end 

效果很好

为什么会这样?

我觉得你需要写def self.available_currencies

您尝试在 class 中创建其他方法,并且 Ruby 在循环中搜索 class 方法 .available_currencies

您必须将 class 方法 .available_currencies 更改为实例方法 #available_currencies 或在初始化程序中创建方法。

方法一:

class MyClass
  def self.available_currencies
    # Your logic...
  end

  # Your logic...
end

方法二:

class MyClass
  def init
    available_currencies.each do |c|
      define_method(c) do
        # Whatever you want to do ...
      end
    end
  end

  def available_currencies
    # Your logic...
  end
end

我建议您使用第一种方式,因为您可能想使用 classes 中的货币。如果你想为不同的实例使用不同的货币,我会推荐你​​第二种方式。

编码愉快:)