我一直在制作游戏(更多的是网络玩具,如果有的话)需要很长的国家/地区进行模拟,而且我已经设法让它上班,但我可以&#39 ;但是我觉得我的解决方案既不是Rubyish也不是优雅的方式。
代码看起来有点像这样:
class Countries
include Singleton
def get(tag)
return eval "@#{tag}"
end
def initialize
@array = []
@afghanistan = Country.new("Afghanistan", [:authoritarian, :reactionary, :sunni, :capitalist, :militarist, :southern_asia, :unstable])
@afghanistan.gdp = 20444
@afghanistan.population = 26023
@array << :afghanistan
@albania = Country.new("Albania", [:hybrid, :conservative, :sunni, :capitalist, :pacifist, :southern_europe])
@albania.gdp = 13276
@albania.population = 2893
@array << :albania
#and so on and so forth
end
attr_accessor :array
end
countries = Countries.instance
puts countries.get("usa").name
puts
for i in 0..(countries.array.size-1)
puts countries.get(countries.array[i]).name
end
我得到
的预期输出United States
Afghanistan
Albania
Algeria
...
但理想情况下,优雅的解决方案不需要.get(),这看起来似乎不像解决这个问题的类似Ruby的方式。这样做有更好的练习方法吗?
我主要从Stack Overflow,Ruby文档和测试中了解到我所知道的一点点,所以我很可能在此过程中违反了许多最佳实践。 Country类的初始值设定项为名称和要添加的标记数组使用字符串,而其他属性则用于添加到单独的行中。
答案 0 :(得分:3)
我会将国家/地区的详细信息存储在文件(e.q. countries.yml或csv文件)或数据库中:
# in countries.yml
afganistan:
name: Afganistan
tags:
- authoritarian
- reactionary
- sunni
- capitalist
- militarist
- southern_asia
- unstable
gdp: 20444
population: 26023
albania:
name: Albania
tags:
...
...
然后你的课程简化为:
require 'yaml'
class Countries
include Singleton
def get(country)
@countries[country]
end
def initialize
@countries = {}
YAML.load_file('countries.yml').each do |country_key, options|
country = Country.new(options['name'], options['tags'])
country.gdp = options['gdp']
country.population = options['population']
@countries[country_key] = country
end
@countries.keys # just to keep the interface compatible with your example
end
end
答案 1 :(得分:2)
您可以通过数百种方法来干扰代码,但您的错误基本上不是使用hash data stucture(或建议的外部文件)。
我就是这样做的,我做了一些假设,希望这有帮助!
# I'll assume that Country is an actual class with a purpose, and not a simple
# structure.
Country = Struct.new(:name, :tags, :gdp, :population)
# list of all the countries
COUNTRIES_TABLE = [
["Afghanistan", [:authoritarian, :reactionary], 20444, 26023],
["Albania", [:hybrid, :conservative], 13276, 2893]
# etc..
]
COUNTRIES = COUNTRIES_TABLE.map { |e| Country.new(*e) }
# we could have directly defined the hash instead of a table, but this keeps
# everything more DRY
COUNTRIES_HASH = COUNTRIES.map {|e| [e.name, e]}.to_h
puts COUNTRIES_HASH["Albania"].name
COUNTRIES_HASH.map do |k,v|
puts v.name
end