I want to ask users to type in a password, but i dont want the chars to appear on screen as they type.
How do I do this in Ruby?
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're on a system with stty
:
`stty -echo`
print "Password: "
pw = gets.chomp
`stty echo`
puts ""
You can use the STDIN.noecho method from the IO/console module:
require 'io/console'
pw = STDIN.noecho(&:gets).chomp
Similar answer as glenn but more complete: http://dmathieu.com/articles/development/ruby-console-ask-for-a-password/
This is solution for UNIX systems:
begin
system "stty -echo"
print "Password: "; pass1 = $stdin.gets.chomp; puts "\n"
print "Password (repeat): "; pass2 = $stdin.gets.chomp; puts "\n"
if pass1 == pass2
# DO YOUR WORK HERE
else
STDERR.puts "Passwords do not match!"
end
ensure
system "stty echo"
end
There is a gem for such user interaction: highline.
password = ask("Password: ") { |q| q.echo = false }
Or even:
password = ask("Password: ") { |q| q.echo = "*" }