Ruby $stdin.gets without showing chars on screen

前端 未结 6 1950
北海茫月
北海茫月 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}"
    
    0 讨论(0)
  • 2020-12-30 00:52

    If you're on a system with stty:

    `stty -echo`
    print "Password: "
    pw = gets.chomp
    `stty echo`
    puts ""
    
    0 讨论(0)
  • 2020-12-30 00:55

    You can use the STDIN.noecho method from the IO/console module:

    require 'io/console'
    pw = STDIN.noecho(&:gets).chomp
    
    0 讨论(0)
  • 2020-12-30 01:02

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

    0 讨论(0)
  • 2020-12-30 01:04

    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
    
    0 讨论(0)
  • 2020-12-30 01:05

    There is a gem for such user interaction: highline.

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

    Or even:

    password = ask("Password:  ") { |q| q.echo = "*" }
    
    0 讨论(0)
提交回复
热议问题