【问题标题】:Get single char from console immediately [duplicate]立即从控制台获取单个字符 [重复]
【发布时间】:2011-11-09 22:24:32
【问题描述】:

是否可以从 STDIN 中获取每个字符(无需等待返回键)?

【问题讨论】:

  • stdin 不一定(甚至通常)是 tty。

标签: ruby


【解决方案1】:

这可以通过 Ruby 1.9.3 的新 getch 方法实现:

require 'io/console'
input = STDIN.getch

文档(核心):http://ruby-doc.org/core-2.3.0/IO.html#class-IO-label-io-2Fconsole

文档(库):http://ruby-doc.org/stdlib-2.3.0/libdoc/io/console/rdoc/IO.html#method-i-getch

来源:https://github.com/ruby/ruby/tree/trunk/ext/io/console

【讨论】:

  • 指向文档的指针会很有帮助。
  • 谢谢,在此回答您:stackoverflow.com/a/20081966/8047
  • 如果你在循环中不要忘记添加exit if input=="\u0018" or input=="\u0003"
【解决方案2】:

是的,有很多方法可以做到这一点,除了 gems,您还可以通过 gems 直接使用 terminfo 操作 termios、ncurses 或 stty 程序。

tty_param = `stty -g`
system 'stty raw'

a = IO.read '/dev/stdin', 1

system "stty #{tty_param}"

print a

【讨论】:

  • 这应该被弃用,有利于@J-_-L 的回答。
【解决方案3】:

使用Highline gem:

require "highline/system_extensions"  # gem install highline
include HighLine::SystemExtensions

print "Enter one character:  "
char = get_character
puts char.chr

来自JEG II's blog

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多