今天才發現原來有個 Ruby Quiz 網站,在上面每週會提供一個題目讓你思考及練習 Ruby programming 的技巧,對於有 programming language 的經驗但是沒有接觸過 Ruby 的人應該是不錯的學習方式。正如同網站所述:We use the Ruby Quiz to learn more about the Ruby programming language, not as a race. 就把它當作遊戲來玩玩吧。

這是我對 Quiz #28: Mad Libs 的解答:

class MadLibs

  def ask(word)
    print "Give me #{word}: "
    $stdin.gets.chomp
  end

  def play(file)
    keywords = {}
    story = file.read.gsub(/\(\((.+?)\)\)/) do
      word = $1
      if word =~ /(.+):(.+)/
        keywords[$1] = ask($2)
      elsif keywords.include?(word)
        keywords[word]
      else
        ask(word)
      end
    end

    puts
    print story
  end

end

raise "No template is given!" if ARGV.length < 1

File.open(ARGV[0]) do |file|
  MadLibs.new.play(file)
end