Ruby - How To Mask a Command-line Password

September 15, 2014

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?

Enter Highline:

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.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus