私の理解では、すべてのハッシュ値は配列であり、それらの配列の要素はランダムに選択されます。ランダムに選択された要素が配列の場合、その配列に含まれるすべての単語が文で使用され、その配列のハッシュキーはそのハッシュキーの値のランダムに選択された要素に置き換えられます。
コード
def random_words(h, key)
h[key].map { |obj| recurse(h,obj) }.join(' ')
end
def recurse(h, obj)
case obj
when Array
obj.map { |o| recurse(h, o) }
when /\<.+?\>/
recurse(h, h[obj].sample)
else
[obj]
end
end
例
例1
h = { "<start>" =>[["The", "<object>", "<verb>", "tonight."]],
"<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]],
"<verb>" =>[["sigh", "<adverb>"], ["portend", "like", "<object>"],
["die", "<adverb>"]],
"<adverb>"=>[["warily"], ["grumpily"]]
}
random_words(h, "<start>")
#=> "The waves portend like slugs tonight."
random_words(h, "<start>")
#=> "The big yellow flowers sigh warily tonight."
random_words(h, "<start>")
#=> "The slugs die warily tonight."
random_words(h, "<object>")
#=> "waves big yellow flowers slugs"
random_words(h, "<verb>")
#=> "sigh warily portend like waves die warily"
random_words(h, "<adverb>")
#=> "warily grumpily"
例2
h = { "<start>" =>[["The", "<object>", "<verb>", "tonight."]],
"<object>"=>[["waves"], ["big", "<verb>", "yellow", "flowers"], ["slugs"]],
"<verb>" =>[["sigh", "<adverb>"], ["portend", "like", "<object>"],
["die", "<start>", "<adverb>"]],
"<adverb>"=>[["warily", "<object>"], ["grumpily"]]
}
random_words(h, "<start>")
#=> "The big sigh grumpily yellow flowers die The waves sigh grumpily \
# tonight. grumpily tonight."
random_words(h, "<start>")
#=> "The big die The big die The slugs sigh grumpily tonight. grumpily \
# yellow flowers die The big sigh warily slugs yellow flowers die The \
# slugs die The slugs portend like big portend like big sigh grumpily \
# yellow flowers yellow flowers tonight. grumpily tonight. grumpily \
# tonight. warily waves tonight. warily big die The slugs sigh warily \
# big sigh grumpily yellow flowers tonight. warily big portend like big \
# portend like waves yellow flowers yellow flowers yellow flowers yellow \
# flowers sigh warily waves tonight."
例3
h = { "<g1>"=>[["It", "<g2>", "<g3>", "..."]],
"<g2>"=>[["of"], ["waves"], ["was the", "<g3>", "<g4>", "<g3>"],
["wisdom,"], ["foolishness,"]],
"<g3>"=>[["<g4>", "of", "<g2>"], ["it", "<g2>"]],
"<g4>"=>[["best"], ["worst"], ["age"], ["times,"]]
}
random_words(h, "<g1>")
#=> "It of it was the it was the it was the times, of foolishness, times, \
# it wisdom, best best of was the it of times, it was the times, of of \
# best it waves worst age of waves ..."
random_words(h, "<g1>")
#=> "It was the best of times, it was the worst of times, it was the age of \
# wisdom, it was the age of foolishness...
あなたの質問は時期尚早です。試してみると分かりませんが、あなたが遭遇した特定の問題に関する詳細な質問を使って、あなたの実装方法を#TODO:あなたの実装を解決しようとした方法を教えてください。コード。 "[どのくらいの研究努力がスタックオーバーフローのユーザーに期待されていますか?](http://meta.stackoverflow.com/q/261592)" –
私は解決策を求めていません。今は2週間ルビーを学んでいます。それについてルビーでどうやって行くのか慣れていない。これがJavaで行われるのであれば、この機能を書くのに苦労することはありません。 –