The three rules of Ruby Quiz:
1. Please do not post any solutions or spoiler discussion for this quiz until
48 hours have passed from the time on this message.
2. Support Ruby Quiz by submitting ideas as often as you can:
3. Enjoy!
···
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
When you stop and think about it, methods like gets(), while handy, are still
pretty low level. In running Ruby Quiz I'm always seeing solutions with helper
methods similar to this:
# by Markus Koenig
def ask(prompt)
loop do
print prompt, ' '
$stdout.flush
s = gets
exit if s == nil
s.chomp!
if s == 'y' or s == 'yes'
return true
elsif s == 'n' or s == 'no'
return false
else
$stderr.puts "Please answer yes or no."
end
end
end
Surely we can make something like that better! We don't always need Rails or a
GUI framework and there's no reason writing a command-line application can't be
equally smooth.
This week's Ruby Quiz is to start a module called HighLine (for high-level,
line-oriented interface). Ideally this module would eventually cover many
aspects of terminal interaction, but for this quiz we'll just focus on getting
input.
What I really think we need here is to take a page out of the optparse book.
Here are some general ideas:
age = ask("What is your age?", Integer, :within => 0..105)
num = eval "0b#{ ask( 'Enter a binary number.',
String, :validate => /^[01_]+$/ ) }"
if ask_if("Would you like to continue?") # ...
None of these ideas are etched in stone. Feel free to call your input method
prompt() or use a set of classes. Rework the interface any way you like. Just
be sure to tell us how to use your system.
The goal is to provide an easy-to-use, yet robust method of requesting input.
It should free the programmer of common concerns like calls to chomp() and
ensuring valid input.