Ruby 控制台逐字符输入

问题描述 投票:0回答:1

我想在一行中获取一个数字输入字符串(5的倍数),但是在每5个数字的块之后,将打印一个空格分隔符,以使输入行更易于阅读和计数。

例如:

在下面输入长度为25位的随机数字键:

45325 89345 98834 23453 23453

而不是:

在下面输入长度为25位的随机数字键:

4532589345988342345323453

这有可能吗?


我尝试使用 getc 读取字符,但收到错误消息:

main:Object 的未定义局部变量或方法“getc”(NameError)

ruby input io console console-application
1个回答
0
投票

你可以这样做:

require 'io/console'

cnt=0
while cnt<25 do
    c=STDIN.getch 
    if c=~/[0-9]/ then 
        print c
        print " " if (cnt+=1)%5==0
    else
        IO::console::beep
    end
end 
© www.soinside.com 2019 - 2024. All rights reserved.