Ruby:常量,模块,哈希

isw*_*swg 0 ruby module constants

我花了几个月的时间学习Ruby,现在我正在尝试构建一个韩语/朝鲜语/英语词典类型的东西.我正在给它一个包含所有单词的文本文件.

到目前为止我有:

module Dictionary

  DICTIONARY = []

end

class File

  include Dictionary

  def self.convert(file)
    readlines(file).each do |line|
      south, north, meaning = line.split(',')
      DICTIONARY << { :south => south, :north => north, :meaning => meaning }
    end
  end

end

File.convert("dictionary.txt")

Dictionary::DICTIONARY.sort_by { |word| word[:north] }.each do |word|
  puts "#{word[:south]} is #{word[:north]} in North Korean. They both mean #{word[:meaning]}"
end
Run Code Online (Sandbox Code Playgroud)

我的问题是:

1)我不必为阵列制作单独的模块吗?(我主要是尝试在模块和类中进行混合)

2)正确使用数组的常量吗?我想我的思维过程就是我希望从外面访问数组,但老实说我真的不知道我在做什么.

提前致谢.

Aet*_*rus 6

由于您的字典是从文件加载的,因此最好使用类而不是模块,这样每个文件都可以解析为单独的字典.

class Dictionary
  attr_reader :content

  def initialize
    @content = []
  end

  def self.load(path)
    instance = new
    File.open(path) do |f|
      f.each_line do |line|
        instance.content << %i(south, north, meaning).zip(line.split(','))
      end
    end
    instance
  end
end
Run Code Online (Sandbox Code Playgroud)

此外,您可以看到我没有修补File该类,因为File它不仅用于创建字典,还用于各种文件操作.