lundi 30 octobre 2017

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

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...,etc. But problem is how to randomly pick values in hash to generate the sentence?

Now I have a hash here:

hash = {"<start>"=>[["The", "<object>", "<verb>", "tonight."]],
        "<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]], 
        "<verb>"=>[["sigh", "<adverb>"], ["portend", "like", "<object>"],["die", "<adverb>"]], 
        "<adverb>"=>[["warily"], ["grumpily"]]}

The Objective is to assemble the strings using random values in the hash for example when the function iterates to "<object>", it will take it as a key and search in the hash to find matching key then randomly pick the corresponding values (one of the strings in "<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]]) and assemble it, then the output would be something like this:

"The waves sigh warily portend like yellow die grumpily tonight" 

My code so far:

hash.each do |_, value|
  value.map{|x| x.map{|y| is_non_terminal?(y) ? (puts value.values_at("SomethingToPutInto")) : (puts y)}}
end

Somehow the logics in the code becomes too complicated and I'm stuck on this step.. Using values_at will cause TypeError: no implicit conversion of String into Integer (TypeError)

For is_non_terminal?(y) is just a function to check whether the string contains < and >:

def is_non_terminal?(s)
   s.include?('<' && '>') ? true : false
end




Aucun commentaire:

Enregistrer un commentaire