Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby $stdin.gets without showing chars on screen

Tags:

ruby

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?

like image 261
Andrew Bullock Avatar asked Sep 13 '10 09:09

Andrew Bullock


4 Answers

You can use the STDIN.noecho method from the IO/console module:

require 'io/console'
pw = STDIN.noecho(&:gets).chomp
like image 107
Droj Avatar answered Nov 15 '22 05:11

Droj


If you're on a system with stty:

`stty -echo`
print "Password: "
pw = gets.chomp
`stty echo`
puts ""
like image 25
glenn jackman Avatar answered Nov 15 '22 05:11

glenn jackman


There is a gem for such user interaction: highline.

password = ask("Password:  ") { |q| q.echo = false }

Or even:

password = ask("Password:  ") { |q| q.echo = "*" }
like image 41
Konstantin Haase Avatar answered Nov 15 '22 06:11

Konstantin Haase


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}"
like image 38
listrophy Avatar answered Nov 15 '22 05:11

listrophy