I've been working on a game (more of a web toy if anything) that requires a long list of countries to simulate, and I've managed to get it to work, but I can't help but feel that my solution is neither a Rubyish nor elegant way of doing it.
The code looks a bit like this:
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
And I get the expected output of
United States
Afghanistan
Albania
Algeria
...
But ideally an elegant solution would not require .get(), and this really doesn't seem like a Ruby-like way of solving this issue. Is there a better-practice way of doing this?
I mostly learned the little bit I know from Stack Overflow, the Ruby docs, and testing, so it's very possible I have violated a lot of best practices along the way. The Country class's initializer takes a string for the name and an array of tags to add, while other properties are intended to be added in separate lines.