mardi 12 février 2019

Ruby, iterating over a multi-value Hash using if/else, trying to return key/value pairs, fails when value is not found

I am trying to scan a string of raw input from a user and return a sentence that's composed of an array of arrays with the (TOKEN, WORD) pairings. If a word isn't part of the lexicon, then it should still return the WORD but set the TOKEN to an error token.

Inside the method "@@dictionary.each do |type, list|" the initial if statement works fine at building a key/value array of found words, as long as the else statement is set to return nil. However, when I try and place error/words pairs into the array for the words not contained in the @@dictionary hash (i.e. those that fall into the else part of the code), I receive 5 separate pairs in the array for each word that the user entered, one for each iteration over each key for each word entered.

Does anybody have an idea how to return just one error/value pair to the array, instead of one for each of the five iterations for every word?

class Lexicon

@@dictionary = {
  'direction' => ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'],
  'verbs' => ['go', 'stop', 'kill', 'eat'],
  'stop words' => ['the', 'in', 'of', 'on', 'at', 'it'],
  'nouns' => ['door', 'bear', 'princess', 'cabinet'],
  'numbers' => [0..9]
}

stuff = $stdin.gets.chomp
@@words = stuff.split(' ')

    def self.scan
        result = []

        @@words.each do |text_element|
            categorized = []

            @@dictionary.each do |type, list|
                if
                    list.include?(text_element.downcase)
                    categorized = [type, text_element]
                    result.push(categorized)
                else
                    nil
                    #categorized = ["ERROR", text_element]
                    #result.push(categorized)
                end
            end
        end
        print result
    end

Lexicon.scan

end

Aucun commentaire:

Enregistrer un commentaire