在我的lib / assets / country_codes.rb文件中:
# 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
s.t.它就像“阿富汗”。但是,它目前已添加,如上面的代码,如“AF”。
我想对平面文件执行查找,以便将“AF”替换为“阿富汗”。
我当前的问题只是我在引用哈希对象时遇到了麻烦。当我尝试访问
时puts "#{CountryCodes.country_codes.AF}"
我的回复是:
undefined method `country_codes' for CountryCodes:Class
如何访问lib / assets / country_codes.rb文件中的哈希对象?
答案 0 :(得分:2)
将其更改为类方法,例如:
class CountryCodes
def self.country_codes
# This is a class method, you call it on the class.
# Example:
# CountryCodes.country_codes[:AF]
{ AF: "Afghanistan",
AL: "Albania" }
end
def country_codes
# This is an instance method. You call it on an instance.
# It just runs the class method, right now.
# You might use it like this:
# c = CountryCodes.new
# c.country_codes
self.class.country_codes
end
end
您需要将其称为:
puts CountryCodes.country_codes[:AF]