Ruby on rails 模块的未定义局部变量或方法
我有一个模块Ruby on rails 模块的未定义局部变量或方法,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有一个模块CurrencyExchange,使用以下方法 CURRENCIES = %w(uah rub eur usd) def available_currencies CURRENCIES.join(' ').downcase.split.permutation(2) end 当我想使用可用货币时 定义方法 available_currencies.each do |(c1, c2)| define_method(:"#{c1}_to_#{c2}") do |c
CurrencyExchange
,使用以下方法
CURRENCIES = %w(uah rub eur usd)
def available_currencies
CURRENCIES.join(' ').downcase.split.permutation(2)
end
当我想使用可用货币时
定义方法
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\u currencies
您尝试在类中创建其他方法,Ruby在循环中搜索类方法。available\u currencies
您必须将类方法.available_currencies
更改为实例方法#available_currencies
,或者在初始值设定项中创建方法
方法1:
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
方法2:
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
我会推荐你第一种方法,因为你可能想在课堂上使用货币。我建议您使用第二种方法,例如,如果您需要针对不同实例使用不同的货币
快乐编码:)当前的逻辑存在一些问题。请将
currency\u exchange.rb
完整文件粘贴到此处。您的代码看起来不错。当你发现问题时,别忘了回答+1用于排列:)