$ ri IO.noecho
(from ruby core)
------------------------------------------------------------------------------
io.noecho {|io| }
------------------------------------------------------------------------------
Yields self with disabling echo back.
STDIN.noecho(&:gets)
will read and return a line without echo back.
For 1.9.3 (and above), this requires you adding require 'io/console' to your code.
正如前面提到的,您可以使用 IO#noecho for Ruby > = 1.9。如果你想要支持1.8,你可以使用 read内置的 shell 函数:
begin
require 'io/console'
rescue LoadError
end
if STDIN.respond_to?(:noecho)
def get_password(prompt="Password: ")
print prompt
STDIN.noecho(&:gets).chomp
end
else
def get_password(prompt="Password: ")
`read -s -p "#{prompt}" password; echo $password`.chomp
end
end
现在获取密码就像下面这样简单:
@password = get_password("Enter your password here: ")