iswg
iswg

Reputation: 195

Ruby: constant, module, hash

I'm a few months into learning Ruby, and right now I'm trying to build a South Korean/North Korean/English dictionary type of thing. I'm feeding it a text file that has all the words.

So far I've got:

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

My question is:

1) Is it unnecessary for me to make a separate module for the array? (I was mostly just trying to experiment with mixing in modules and classes)

2) Is using a constant for the array the right move? I guess my thought process was that I wanted the array to be able to be accessed from outside, but to be honest I don't really know what I'm doing.

Thanks in advance.

Upvotes: 0

Views: 668

Answers (1)

Aetherus
Aetherus

Reputation: 8888

Since your dictionary is loaded from a file, it's better to have a class instead of a module so each file can be parsed to a separate dictionary.

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

Besides, you can see I didn't patch the File class because File is not only for creating dictionaries, but for all sorts of file manipulation.

Upvotes: 6

Related Questions