Ruby $stdin.gets without showing chars on screen

前端 未结 6 1961
北海茫月
北海茫月 2020-12-30 00:21

I want to ask users to type in a password, but i dont want the chars to appear on screen as they type.

How do I do this in Ruby?

6条回答
  •  礼貌的吻别
    2020-12-30 00:45

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

提交回复
热议问题