Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby控制台:如何保持';获取';从用户输入时添加新行开始_Ruby - Fatal编程技术网

Ruby控制台:如何保持';获取';从用户输入时添加新行开始

Ruby控制台:如何保持';获取';从用户输入时添加新行开始,ruby,Ruby,为什么get在用户输入框数时总是添加新行 我希望下一个print语句显示在与输入相同的行上 print "Enter the number of boxes: " boxes = gets.chomp print "Enter number of columns to print the boxes in: " columns = gets.chomp 我希望输出如下所示: Enter the number of boxes: 47 Enter number o

为什么
get
在用户输入框数时总是添加新行

我希望下一个print语句显示在与输入相同的行上

    print "Enter the number of boxes: "
    boxes = gets.chomp
    print "Enter number of columns to print the boxes in: "
    columns = gets.chomp
我希望输出如下所示:

Enter the number of boxes: 47 Enter number of columns to print the boxes in: 4

在收到第二个输入之前,我不想开始新的一行。

在windows中,您可以这样做,否则您将需要一个类似的read\u char方法,在您的操作系统中工作

def read_char #only on windows
  require "Win32API"
  Win32API.new("crtdll", "_getch", [], "L").Call
end

def get_number
  number, inp = "", 0
  while inp != 13
    inp = read_char
    if "0123456789"[inp.chr]
      number += inp.chr
      print inp.chr  
    end
  end
  number
end

print "Enter the number of boxes: "
boxes = get_number
print " Enter number of columns to print the boxes in: "
columns = get_number
puts ""

puts "boxes: #{boxes}"
puts "columns: #{columns}"

# gives
# Enter the number of boxes: 5 Enter number of columns to print the boxes in: 6
# boxes: 5
# columns: 6

您需要使用IO/console,并一次将输入设置为一个字符:

require 'io/console'

def cgets(stream=$stdin)
  $stdin.echo = false
  s = ""
  while true do
    c = stream.getc
    return s if c == "\n"
    s << c
  end
end
需要“io/控制台”
def cgets(流=$stdin)
$stdin.echo=false
s=“”
尽管如此
c=stream.getc
如果c==“\n”则返回s

s Nathan,这个问题不是很容易缓解的。但是想想看,在用户输入47之后,他们会按什么?你是说使用返回键本身就是传递换行符的方式吗?是否可以创建一个方法来附加gets(gets.nonewline)以删除换行符?我不确定这是否真的值得付出努力?好的,我将所有内容都集中到一个以逗号分隔的打印语句中。输出是正确的,但当脚本运行时,不会打印任何内容,它会先等待两个输入,然后运行print语句。输出为~./框20 2输入要打印的框数:20输入列数:2