Reputation: 5921
I am writing a code that is supposed to read from STDIN exactly n number of times.So lets say 3 times.What is the best way to do that ?
I tried this
counter = 0
while sentence = gets.chomp && counter < 3 do
...
counter += 1
end
but for some strange reason, sentence variable inside loop is Boolean ?
Upvotes: 0
Views: 70
Reputation: 27227
Operator precedence. The line:
while sentence = gets.chomp && counter < 3 do
Is being interpretted as
while sentence = ( gets.chomp && counter < 3 ) do
So, you could do this:
while ( sentence = gets.chomp ) && counter < 3 do
That explains why you got true
or false
values into sentence
, and the third option should fix this, so your code is very close to working. However, it is probably more usual in Ruby to see solutions like Babai's
Upvotes: 1
Reputation: 118299
You can do as below:
n.times { sentence = gets.chomp }
or
n.times do
sentence = gets.chomp
# your code here
end
Upvotes: 2