Ruby - How To Mask a Command-line Password
When writing command-line applications, one thing you might need is a user’s password. Obviously a password prompt should be masked or at least hidden from anyone who might walk past you. So how do we do this in Ruby without breaking a sweat?
HighLine was designed to ease the tedious tasks of doing console input and output with low-level methods like gets() and puts(). HighLine provides a robust system for requesting data from a user, without needing to code all the error checking and validation rules and without needing to convert the typed Strings into what your program really needs. Just tell HighLine what you're after, and let it do all the work.
Running this and typing in ‘password’ will output:
Hey dude choose a password: ******** Your password is 'password'
So just install the ‘highline’ gem, create a method that takes a message and a mask. The mask will be printed to the screen every time you type a character. Then call this method passing in your message and bam you can hide the characters as they are type.