将多个值附加到空哈希中的一个键

时间:2015-03-04 00:17:28

标签: ruby string hash

我试图在数组中找到与文件中字典单词最匹配的字符串。我将得分(匹配)存储为哈希的键,并将相应的匹配字符串存储为键的值。例如:

  • 字符串"XXBUTTYATCATYSSX"有三个子字符串字匹配。此字符串的分数为3。字符串和分数存储在scores哈希中:

    scores = { 3 => "XXBUTTYATCATYSSX" }
    
  • 字符串"YOUKKYUHISJFXPOP"也有三个匹配项。这应该存储在哈希中:

    scores = { 3 => "XXBUTTYATCATYSSX", "YOUKKYUHISJFXPOP" }
    

"

scores = { }
#scores = Hash.new { |hash, key| hash[key] = [] }
File.open("#{File.dirname(__FILE__)}/dictionary.txt","r") do |file|
  #going to a string in the array
  strArray.each_index do |str|
    score = 0
    match = strArray[str]
    #going to a line in the dictionary file
    file.each_line do |line|
      dictWord = line.strip!.upcase
      if match.include? dictWord
        score += 1
      end
    end
    #the key in the scores hash equals the score (amount of matches)
    #the values in the scores hash are the matched strings that have the score of the key
    #scores[score] << match
    scores.merge!("#{score}" => match)
end

编辑: 我修改了上面的代码。现在它不会在第一个循环后进入file.each_line do |line|

请帮忙。

2 个答案:

答案 0 :(得分:1)

使用File个对象,您无法读取它们两次。也就是说,如果您使用each_line读取整个文件一次,那么您尝试再次执行此操作,第二次不会做任何事情,因为它已经在文件的末尾。要再次阅读该文件,您需要先使用file.rewind进行回放,然后再尝试阅读该文件。

第二个问题是你试图添加到一个不存在的数组。例如:

scores = {}
scores[3] #=> nil
scores[3] << 'ASDASDASD' # crashes (can't use << with nil)

您需要为每个分数创建一个数组,然后才能向其添加单词。一种方法是在使用密钥之前检查密钥是否存在,如下所示:

scores = {}
if scores[3].nil?
  scores[3] = []
end
scores[3] << 'word' # this will work

答案 1 :(得分:0)

直接代码:

scores = Hash.new

File.open("#{File.dirname(__FILE__)}/dictionary.txt","r") do |file|
  strings.each do |string|
    score = 0
    file.each do |line|
      score += 1 if string.match(line.strip!.upcase)
    end
    # store score and new array unless it already have same score
    scores.store(score, []) unless scores.has_key?(score)
    scores[score] << string
    # rewind to read dictionary from first line on next iteration
    file.rewind
  end
end

strings是您要与dict进行比较的字符串数组:

e.g。 strings = ["XXBUTTYYOUATCATYSSX", "YOUKKYUHISJFXPOP"]