Ruby $ stdin.gets没有在屏幕上显示字符

我想要求用户输入密码,但我不希望字符在键入时显示在屏幕上。

我如何在Ruby中执行此操作?

这种用户交互有一个gem: 高线 。

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

甚至:

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

如果你在使用stty的系统上:

 `stty -echo` print "Password: " pw = gets.chomp `stty echo` puts "" 

您可以使用IO /控制台模块中的STDIN.noecho方法:

 pw = STDIN.noecho(&:gets).chomp 

您希望确保您的代码是幂等的……此处列出的其他解决方案假设您希望在重新开启echo的情况下退出此function块。 那么,如果在输入代码之前关闭它会怎样,并且预计会保持关闭状态?

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

这是UNIX系统的解决方案:

  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 

与glenn类似的答案,但更完整: http : //dmathieu.com/articles/development/ruby-console-ask-for-a-password/