I'm trying to look through a dictionary file and compare it to a string in an array. In order to find the string that has the most matches to dictionary words I've decided to store the "score" (aka matches) as the key of a hash and have the strings that have that amount of matches as the value to the key. For example:
- The string "XXBUTTYATCATYSSX" has 3 substring word matches
- The score for this string would be 3
- The string and score get stored into the "scores" hash as:
scores = { 3 => "XXBUTTYATCATYSSX" } - Now the next string "YOUKKYUHISJFXPOP" also has 3 matches
This should be stored in the hash as:
scores = { 3 => "XXBUTTYATCATYSSX", "YOUKKYUHISJFXPOP" }scores = Hash.new(1) #scores = Hash.new { |hash, key| hash[key] = [] } File.open("#{File.dirname(__FILE__)}/dictionary.txt","r") do |file| #going to a string in the array ptArray.each_index do |str| score = 0 match = ptArray[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 end
I'm having an error of "no implicit conversion of String into Integer" with the appending line scores.merge(scores[score] << match)
Also when I tried taking out scores = Hash.new(1) and using scores = Hash.new { |hash, key| hash[key] = [] } in combination with scores[score] << match before the last end It kept skipping over the loop that goes through the dictionary file, so the score would continuously be 0 leading to the rest of the strings being stored in the hash key scores[0]. But it would technically do the appending I am looking for.
Using plain old scores[score] << match gave an error of "no implicit conversion of String into Integer".
Please help! I'm almost done with this assignment, just need to figure this bit out. Thanks in advance! :)
PS: apologies for the code formatting above, some of the comment characters were throwing it off.
Aucun commentaire:
Enregistrer un commentaire