Question

I have made a hash table of English Words and their values from a text file by parsing the first word from each line as the word to be defined and all words but the but the first as the definition, using this code:

words = Hash.new
File.open("path/dictionary.txt") do|file|
  file.each do |line|
    n = line.split.size
definition = line.strip[/(?<=\s).*/]
    words[line.strip.split[0...1]] = definition
  end
end

However, when I try to print a value using code such as this:

p words["Definition"]

It prints 'nil'. I am still able to print the whole hashtable using 'p words' so I dont understand. Any ideas? Thanks

EDIT: Here is the beginning of dictionary.txt to give you an idea of what I'm doing:

A-  prefix (also an- before a vowel sound) not, without (amoral). [greek]

Aa  abbr. 1 automobile association. 2 alcoholics anonymous. 3 anti-aircraft.

Aardvark  n. Mammal with a tubular snout and a long tongue, feeding on termites. [afrikaans]

Ab-  prefix off, away, from (abduct). [latin]

Aback  adv.  take aback surprise, disconcert. [old english: related to *a2]

Abacus  n. (pl. -cuses) 1 frame with wires along which beads are slid for calculating. 2 archit. Flat slab on top of a capital. [latin from greek from hebrew]

Abaft  naut. —adv. In the stern half of a ship. —prep. Nearer the stern than. [from *a2, -baft: see *aft]

Abandon  —v. 1 give up. 2 forsake, desert. 3 (often foll. By to; often refl.) Yield to a passion, another's control, etc. —n. Freedom from inhibitions.  abandonment n. [french: related to *ad-, *ban]

Abandoned  adj. 1 deserted, forsaken. 2 unrestrained, profligate.

Abase  v. (-sing) (also refl.) Humiliate, degrade.  abasement n. [french: related to *ad-, *base2]

Abashed  predic. Adj. Embarrassed, disconcerted. [french es- *ex-1, baïr astound]

Abate  v. (-ting) make or become less strong etc.; diminish.  abatement n. [french abatre from latin batt(u)o beat]

Abattoir  n. Slaughterhouse. [french abatre fell, as *abate]

Abbacy  n. (pl. -ies) office or jurisdiction of an abbot or abbess. [latin: related to *abbot]

Abbé  n. (in france) abbot or priest. [french from latin: related to *abbot]

Abbess  n. Head of a community of nuns.

Abbey  n. (pl. -s) 1 building(s) occupied by a community of monks or nuns. 2 the community itself. 3 building that was once an abbey.
Was it helpful?

Solution

Looks like the keys in your hash are arrays with one element.

Change to

words[line.strip.split[0...1][0]]=definition

OTHER TIPS

Since you do not post the text, it is hard to tell what you want, but I guess this is what you want:

words = {}
File.foreach("path/dictionary.txt") do |line|
  words.store(*line.strip.split(/\s+/, 2))
end

If you have empty lines in the text,

words = {}
File.foreach("path/dictionary.txt") do |line|
  words.store(*line.strip.split(/\s+/, 2)) if line =~ /\S/
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top