我想要求用户输入密码,但我不希望这些字符在输入时显示在屏幕上。
我如何在Ruby中执行此操作?
答案 0 :(得分:25)
您可以使用IO /控制台模块中的STDIN.noecho方法:
require 'io/console'
pw = STDIN.noecho(&:gets).chomp
答案 1 :(得分:24)
如果您使用的是stty
:
`stty -echo`
print "Password: "
pw = gets.chomp
`stty echo`
puts ""
答案 2 :(得分:13)
此类用户互动有一个宝石:highline。
password = ask("Password: ") { |q| q.echo = false }
甚至:
password = ask("Password: ") { |q| q.echo = "*" }
答案 3 :(得分:6)
您希望确保您的代码具有幂等性......此处列出的其他解决方案假设您希望在重新启用echo的情况下退出此功能块。那么,如果在输入代码之前关闭它会怎样,并且预计会保持关闭状态?
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}"
答案 4 :(得分:2)
这是 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
答案 5 :(得分:0)