2
在我的lib /资产/ country_codes.rb文件:使用耙子任务中的LIB哈希对象/资产
# lib/assets/country_codes.rb
class CountryCodes
country_codes = {
AF: "Afghanistan",
AL: "Albania",
[...]
}
end
在rake任务,我用:
# lib/tasks/fetch_cities
require '/assets/country_codes'
city = City.create do |c|
c.name = row[:name]
c.country_code = row[:country_code] # row[:country_code] in this case is like "AF"
end
我想添加c.country_code
st它就像“阿富汗”。但是,它目前已添加,如上面的代码中所示,如“AF”。
我想对平面文件执行查找,以便将“AF”替换为“Afghanistan”。
我目前的问题是我只是在引用散列对象时遇到问题。
undefined method `country_codes' for CountryCodes:Class
如何访问的lib /资产/ country_codes.rb文件中的哈希对象:当我尝试访问
puts "#{CountryCodes.country_codes.AF}"
我有回来了?
这看起来太棒了!一旦我确认就会批准答案!为什么'def self.country_codes'而不是'def country_codes'? –
@ColeBittel在代码中添加了解释。 –
当我们将代码传递给类方法时,通常是如何格式化参数。通过这种方式(与方括号),而不是传统参数(parens)的常规方式之间有什么区别? –