Jan E. wrote in post #1054940:
Christopher D. wrote in post #1054934:
Hey, thanks for the reply. I’ve been practising my ruby but if you have
a JSON or XML solution I will look at / learn those too as Ruby is often
used in tandem with XML and JSON
So I’m looking to start up a text file where I can type words and then
its corresponding definition on the same line. For example.
In dictionary.txt I would have
word1 - definition1;
word2 - definition2;
If it’s only one word and one definition per line, then XML or JSON is
probably too much. But I wouldn’t use a hyphen as a separator, because
it may also appear in words or definitions. Use something special like a
double colon:
word :: definition
You don’t have to mark the end of the definition, because you can simply
read the whole line.
The “parser” could be something like this:
dictionary = {}
File.foreach ‘C:/dictionary.txt’ do |line|
next if line.strip.empty? # skip empty lines
parts = line.split(’::’).map &:strip # split line at the double colon
That’s unsafe because it will break if there is a ‘::’ in the
definition.
if parts.length == 2 and parts.none? &:empty?
word, definition = parts
raise “multiple definitions for #{word}” if
dictionary.has_key? word.to_sym
dictionary[word.to_sym] = definition
else
raise “invalid line: #{line}”
end
end
p dictionary
I would separate parsing and dictionary building. For example
def read_dict(file_name)
File.foreach file_name do |line|
line.chomp!
if %r{\A\s*(\w+)\s*::\s*+(.*?)\s*\z} =~ line
yield $1, $2 # word, def
else
raise "invalid line: #{line}"
end
end
end
def load_dict(file_name)
dict = {}
read_dict file_name do |word, definition|
raise “multiple definitions for #{word}” if
dict.has_key? word
dict[word] = definition
end
dict
end
Btw, I wouldn’t use symbols for the words because there are potentially
many and they are not GC’ed.
Kind regards
robert