# save this as guess.rb
words = ['foobar', 'baz', 'quux']
secret = words[rand(3)]
print "guess? "
while guess = STDIN.gets
guess.chop!
if guess == secret
print "You win!\n"
break
else
print "Sorry, you lose.\n"
end
print "guess? "
end
print "The word was ", secret, ".\n"
现在,别太担心代码细节了.下面是谜题程序运行的一个对话.
% ruby guess.rb
guess? foobar
Sorry, you lose.
guess? quux
Sorry, you lose.
guess? ^D
The word was baz.