Random Sentence Generator in Ruby : How to randomly select values on specific key in hash?

前端 未结 2 426
渐次进展
渐次进展 2021-01-27 02:19

I\'m working on a Ruby verison of RSG and somehow stuck on the sentence generating process (...)

so I managed to implement all functions like read, convert to hash...,et

2条回答
  •  旧巷少年郎
    2021-01-27 03:19

    I assume they're looking for a recursive method, let's call it generate.

    def generate(key)
    

    Read the hash at the key and take one randomly using sample:

      words = @hash[key].sample
    

    Then, for each word, check to see if it's a . If so, call generate on it, otherwise save it:

        if (word.start_with?("<") && word.end_with?(">"))
          generate(word)
        else
          @sentence << word
        end
    

    Putting it all together:

    @hash = {""=>[["The", "", "", "tonight."]],
            ""=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]], 
            ""=>[["sigh", ""], ["portend", "like", ""],["die", ""]], 
            ""=>[["warily"], ["grumpily"]]}
    
    @sentence = []
    
    def generate(key)
      words = @hash[key].sample
      words.each do |word|
        if (word.start_with?("<") && word.end_with?(">"))
          generate(word)
        else
          @sentence << word
        end
      end
    end
    
    generate("")
    puts @sentence.join(" ")
    
    
    

    Notice I used @-variables to make their scope reachable from within the method.

    Sample output: The big yellow flowers sigh grumpily tonight.

    提交回复
    热议问题