I Just Want One Character!
Every so often a person asks the question on Ruby Talk, "How can I get just one character from the keyboard (without needing the user to hit return)?" Everyone is always quick to post solutions, but sadly there are some issues with almost every one of them.
The general consensus is that this is a tough problem to solve correctly. I say that's the exact reason to let HighLine handle this for you:
#!/usr/bin/env ruby -w require "highline/system_extensions" include HighLine::SystemExtensions print "Enter one character: " char = get_character puts char.chr
That doesn't look too tough, does it?
What's terrific about this solution is that under-the-hood
HighLine will check your platform and libraries and then try to use the solution that makes the most sense for your environment. The code is really pretty robust too, because people a lot smarter than me have been sending in patches for over a year, slowly eliminating all of those tricky edge cases.
As you can see, I've split this functionality of
HighLine into a separate module so you don't even need to load the full
HighLine system. This was done just because this is such a real and common problem. This section of
HighLine is one pure Ruby file, so feel free to vendor it if the external dependency is an issue.
Trust me, reading individual characters from the keyboard doesn't have to be that tough. You just need the right tool for the job.