Answer to Best of Ruby Quiz quiz 01

Best of Ruby Quiz quiz 01: Mad Libs

results = {}
pattern = /\(\(([^:]*?)\)\)/
=begin
string = "Our favorite language is ((gem:a gemstone)). We think ((gem)) is ((gem01:a gemstone01))\
 better than ((a gemstone))."
=end
string = "I had a ((an adjective)) sandwich for lunch today. It dripped all \
over my ((a body part)) and ((a noun))."

string.gsub(pattern){|s| s.sub!("))", ""); results[s.sub("((", "")] = ""}
results.each do |key, value|
  p key
  results[key] = gets().chomp
  string.gsub!("(("+key+"))", results[key])
  #  string.gsub!("(("+key+"))"){|s| new_results[key]}
end

pattern02 = /\(\((.*?)\:.*?\)\)/
string.gsub!(pattern02) do |s|
  results[$1]
end

p string

你可能感兴趣的:(Ruby)