向类添加许多变量的 Rubyish 方法

标签 ruby coding-style

我一直在开发一款需要模拟一长串国家/地区的游戏(如果有的话,更像是一个网络玩具),并且我已经设法让它工作,但我忍不住觉得我的解决方案既不是 Ruby 也不是优雅的方法。

代码看起来有点像这样:

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 类的初始值设定项采用一个字符串作为名称和一个要添加的标签数组,而其他属性则打算在单独的行中添加。

最佳答案

我会将国家/地区的详细信息存储在文件(例如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

关于向类添加许多变量的 Rubyish 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34320808/

相关文章:

ruby - 为什么我的 jekyll 命令不再起作用了?

java - Checkstyle 报告捕获异常参数的 LocalFinalVariableNameCheck 错误

coding-style - 有作者姓名的代码是绝对必要的吗?

c# - (0 == 变量) 或 (null == obj) : An outdated practice in C#?

ruby - 如何在脚本失败(错误)时继续并使用 Capistrano 3 捕获输出

sql - rails 和 PSQL : how to convert a column of type STRING to UUID with a fallback value

ruby-on-rails - 如何用 Ruby 定义 一天前在 2 :00 PM?

ruby-on-rails - Rails 加载模块链时遇到问题

if-statement - 如何整理过多的 if 语句以提高可读性

c# - 为什么要使用字段而不是属性?