在Ruby中打印哈希表值时出现问题
我从文本文件中创建了一个英文单词及其值的哈希表,通过解析每行中的第一个单词作为要定义的单词,并解析除第一个之外的所有单词作为定义,使用以下代码:在Ruby中打印哈希表值时出现问题,ruby,hashtable,key-value-coding,Ruby,Hashtable,Key Value Coding,我从文本文件中创建了一个英文单词及其值的哈希表,通过解析每行中的第一个单词作为要定义的单词,并解析除第一个之外的所有单词作为定义,使用以下代码: 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
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单词”打印整个哈希表,所以我不明白。有什么想法吗?谢谢
编辑:这里是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.
由于你没有发布文本,很难说出你想要什么,但我猜这就是你想要的:
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
看起来散列中的键是包含一个元素的数组 改为
words[line.strip.split[0...1][0]]=definition
检查区分大小写。如果您添加示例文本(不是真实文本,而是短文本),人们更可能会帮助您以及预期的结果。当你打印整个哈希表时,你会得到什么?你确定文本中有内容的行之间有空行吗?当我打印整个哈希表时,它会打印一个单词及其定义的哈希表
words[line.strip.split[0...1][0]]=definition