2014-02-12 44 views
0

我已經通過解析每行的第一個單詞作爲要定義的單詞以及除第一個單詞之外的所有單詞作爲定義,從文本文件中製作英文單詞及其值的哈希表,使用此代碼:在紅寶石中打印hashtable值的問題

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 

然而,當我嘗試打印使用代碼的值,如本:

p words["Definition"] 

它打印出「零」。我仍然能夠使用'p words'打印整個hashtable,所以我不明白。有任何想法嗎?由於

編輯:這裏是dictionary.txt的開始,給你的我在做什麼的想法:

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. 
+0

檢查大小寫.. –

+2

人們將更有可能幫助你,如果你添加一個示例文本(不是真實的,是短暫的)和預期的結果。 – sawa

+0

當你打印整個散列表時你會得到什麼? –

回答

1

貌似鍵在你的散列是有一個元素的數組。

更改爲

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

既然你不發佈文字,它是很難告訴你想要什麼,但我想這是你想要什麼:

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

如果在文本空行,

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

好點 - 我添加了字典文件的開頭。 –