I want to ask users to type in a password, but I don't want the chars to appear on screen as they type.
How do I do this in Ruby?
You can use the STDIN.noecho method from the IO/console module:
require 'io/console'
pw = STDIN.noecho(&:gets).chomp
If you're on a system with stty
:
`stty -echo`
print "Password: "
pw = gets.chomp
`stty echo`
puts ""
There is a gem for such user interaction: highline.
password = ask("Password: ") { |q| q.echo = false }
Or even:
password = ask("Password: ") { |q| q.echo = "*" }
You want to make sure your code is idempotent... other solutions listed here assume you want to exit this chunk of functionality with echo turned back on. Well, what if it was turned off before entering the code, and it's expected to stay off?
stty_settings = %x[stty -g]
print 'Password: '
begin
%x[stty -echo]
password = gets
ensure
%x[stty #{stty_settings}]
end
puts
print 'regular info: '
regular_info = gets
puts "password: #{password}"
puts "regular: #{regular_info}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With