I'm teaching myself Ruby by rewriting PHP solutions, such as this one. The program should match words in a sentence with a dictionary of synonyms and then make combinations with them.
dict = {
'hello' => ['hey', 'what\'s up'],
'name' => ['nomenclature', 'epithet']
}
str = 'hello, my name is'
class SentenceMaker
def initialize str, dict
@thesaurus = []
@template = str.gsub(/\w+/) {|match|
if (dict[match])
@thesaurus.push dict[match]
'%%%d$s' % @thesaurus.length
else
match
end
}
end
def each
@thesaurus.first.product(*@thesaurus.slice(1..-1)).each {|repl|
yield @template % repl
}
end
end
SentenceMaker.new(str, dict).each {|sentence|
puts sentence
}
Example output
hey, my nomenclature is
hey, my epithet is
what's up, my nomenclature is
what's up, my epithet is
Does this make enough use of the language expressions, or did I miss a few things?