【问题标题】:Trouble printing hashtable values in Ruby在 Ruby 中打印哈希表值时遇到问题
【发布时间】:2014-03-11 01:04:17
【问题描述】:

我通过将每行中的第一个单词解析为要定义的单词以及除第一个单词之外的所有单词作为定义,使用以下代码从文本文件中制作了一个英语单词及其值的哈希表:

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"]

它打印'nil'。我仍然可以使用“p words”打印整个哈希表,所以我不明白。有任何想法吗?谢谢

编辑:这里是 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.

【问题讨论】:

  • 检查区分大小写..
  • 如果您添加示例文本(不是真实的,简短的)和预期结果,人们将更有可能帮助您。
  • 打印整个哈希表会得到什么?
  • 你确定正文中的内容行之间有空行吗?
  • 当我打印整个哈希表时,它会打印单词及其定义的哈希表

标签: ruby hashtable key-value-coding


【解决方案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

【讨论】:

    【解决方案2】:

    看起来哈希中的键是具有一个元素的数组。

    改成

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2019-02-03
      相关资源
      最近更新 更多