Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.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 从STDIN读取数据的特定次数_Ruby - Fatal编程技术网

Ruby 从STDIN读取数据的特定次数

Ruby 从STDIN读取数据的特定次数,ruby,Ruby,我正在写一个代码,它应该从STDIN中读取n次。那么让我们说3次。最好的方法是什么 我试过这个 counter = 0 while sentence = gets.chomp && counter < 3 do ... counter += 1 end 计数器=0 当句子=get.chomp&&counter

我正在写一个代码,它应该从STDIN中读取n次。那么让我们说3次。最好的方法是什么

我试过这个

counter = 0
while sentence = gets.chomp && counter < 3 do
 ...
 counter += 1
end
计数器=0
当句子=get.chomp&&counter<3 do时
...
计数器+=1
结束
但出于某种奇怪的原因,循环中的语句变量是布尔型的?

您可以按如下操作:

n.times { sentence = gets.chomp }

您可以执行以下操作:

n.times { sentence = gets.chomp }


运算符优先级。该行:

while sentence = gets.chomp && counter < 3 do
while语句=get.chomp&&counter<3 do
被解释为

while sentence = ( gets.chomp && counter < 3 ) do
而句子=(gets.chomp&&counter<3)do
所以,你可以这样做:

while ( sentence = gets.chomp ) && counter < 3 do
while(句子=gets.chomp)和&counter<3 do


这就解释了为什么将
true
false
值输入到
语句中,第三个选项应该可以解决这个问题,因此您的代码非常接近正常工作。然而,在Ruby中更常见的可能是看到像Babai的

操作符优先级这样的解决方案。该行:

while sentence = gets.chomp && counter < 3 do
while语句=get.chomp&&counter<3 do
被解释为

while sentence = ( gets.chomp && counter < 3 ) do
而句子=(gets.chomp&&counter<3)do
所以,你可以这样做:

while ( sentence = gets.chomp ) && counter < 3 do
while(句子=gets.chomp)和&counter<3 do

这就解释了为什么将
true
false
值输入到
语句中,第三个选项应该可以解决这个问题,因此您的代码非常接近正常工作。然而,在Ruby中,像Babai这样的解决方案可能更常见