Dominik Bathon
4/17/2005 1:18:00 PM
On Fri, 15 Apr 2005 14:52:15 +0200, Ruby Quiz <james@grayproductions.net>
wrote:
> This week's Ruby Quiz is to write a program that presents the user with
> Madlibs.
> The script should ask the user for a series of words, then fill in the
> proper
> places in the story using the user's answers.
Here is my solution. It is a very simplistic command line interface
version, but it does the job :-)
Just give it the madlib filename as first argument.
The Code:
def ask_for(str)
puts "Give me #{str}:"
$stdin.gets.chomp
end
keys={}
puts "", ARGV[0].split(".")[0].gsub("_", " "),
IO.read(ARGV[0]).gsub(/\(\(([^)]+)\)\)/) {
if (t=$1) =~ /\A([^:]+):(.+)\z/
keys[$1]=ask_for($2)
else
keys[t] || ask_for(t)
end
}
=======================
And here is an even shorter version, that does the same:
keys=Hash.new { |h, k|
puts "Give me #{k.sub(/\A([^:]+):/, "")}:"
h[$1]=$stdin.gets.chomp
}
puts "", $*[0].split(".")[0].gsub("_", " "),
IO.read($*[0]).gsub(/\(\(([^)]+)\)\)/) { keys[$1] }