Ruby 仅一个输入的多行输入
Ruby Multi-Line Input for Only One Input
我有一个正在处理的小程序,我希望用户能够输入可能的多行响应。
我找到了
的示例
$/ = "END"
user_input = STDIN.gets
puts user_input
但这使得所有输入都需要 END 关键字,而我只需要一个输入。
如何只为一个输入生成多行输入?
IO#gets
有一个可选参数,允许您指定分隔符。这是一个例子:
puts "Enter Response"
response = gets.chomp
puts "Enter a multi line response ending with a tab"
response = gets("\t\n").chomp
输出:
Enter Response
hello
Enter a multi line response ending with a tab
ok
how
is
this
此方法接受文本直到第一个空行:
def multi_gets(all_text='')
until (text = gets) == "\n"
all_text << text
end
return all_text.chomp # you can remove the chomp if you'd like
end
puts 'Enter your text:'
p multi_gets
输出:
Enter your text:
abc
def
"abc\ndef"
我用这个:
in = STDIN.readline(sep="\t\n")
puts in
结束输入。有关详细信息,请参阅 https://ruby-doc.org/core-2.2.0/IO.html#method-i-readline
我有一个正在处理的小程序,我希望用户能够输入可能的多行响应。
我找到了
的示例$/ = "END"
user_input = STDIN.gets
puts user_input
但这使得所有输入都需要 END 关键字,而我只需要一个输入。
如何只为一个输入生成多行输入?
IO#gets
有一个可选参数,允许您指定分隔符。这是一个例子:
puts "Enter Response"
response = gets.chomp
puts "Enter a multi line response ending with a tab"
response = gets("\t\n").chomp
输出:
Enter Response
hello
Enter a multi line response ending with a tab
ok
how
is
this
此方法接受文本直到第一个空行:
def multi_gets(all_text='')
until (text = gets) == "\n"
all_text << text
end
return all_text.chomp # you can remove the chomp if you'd like
end
puts 'Enter your text:'
p multi_gets
输出:
Enter your text:
abc
def
"abc\ndef"
我用这个:
in = STDIN.readline(sep="\t\n")
puts in
结束输入。有关详细信息,请参阅 https://ruby-doc.org/core-2.2.0/IO.html#method-i-readline