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

前端 未结 2 449
渐次进展
渐次进展 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

    Code

    def generate(hash, start_key)
      mod_hash = hash.transform_values{ |v| v.map { |a| a.join(' ') } }
      sentence = mod_hash[start_key].sample
      while sentence.include?('<')
        sentence.gsub!(/\<.+?\>/) { |s| mod_hash[s].sample }
      end
      sentence
    end  
    

    Examples

    hash = { "" =>[["The", "", "", "tonight."]],
             ""=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]],
             ""  =>[["sigh", ""], ["portend", "like", ""],
                          ["die", ""]],
             ""=>[["warily"], ["grumpily"]]}
    
    generate(hash, '') #=> "The big yellow flowers die grumpily tonight."
    generate(hash, '') #=> "The waves die warily tonight."
    generate(hash, '') #=> "The slugs sigh warily tonight."
    generate(hash, '')  #=> "portend like big yellow flowers"
    
    
    

    Explanation

    Firstly, mod_hash is constructed.

    mod_hash = hash.transform_values{ |v| v.map { |a| a.join(' ') } }
      #=> {"" =>["The   tonight."],
      #    ""=>["waves", "big yellow flowers", "slugs"],
      #    ""  =>["sigh ", "portend like ", "die "],
      #    ""=>["warily", "grumpily"]}
    
    
    

    Then the initial sentence is obtained.

    start_key = ''
    sentence = mod_hash[start_key].sample
      #=> "The   tonight."
    
    
    

    We now simply replace each word in sentence that begins '<' and ends '>' with a randomly-selected element of the value of that key in mod_hash (the value being an array of strings). This continues until there are no more such words in sentence.

    The question mark in the regex means that one or more characters are to be matched lazily. That means that the match is terminated as soon as the first '>' is encountered. If, for example, the sentence were "a and !", the regex would match both and . By contrast, if the match were greedy (the default), it would match " and ", which of course is not a key of mod_hash.

    Note that hash could have a structure that results in a non-terminating sequence of replacements.

    See Hash#transform_values.

    提交回复
    热议问题