开发者

Ruby $stdin.gets without showing chars on screen

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}"


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


Similar answer as glenn but more complete: http://dmathieu.com/articles/development/ruby-console-ask-for-a-password/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜