Reputation: 79
STDIN.read.split("\n").each do |a|
a=gets.to_i
if a >=0
puts "a is positive"
end
end
Output
C:\Ruby221-x64\programs>ruby test2.rb
5
test2.rb:3:in `read': Interrupt
from test2.rb:3:in `<main>'
Question: Why is my Ruby Code not going into the if?
Also Is the above code a way to handle continuous input? how will my code know after which input to stop. I had to press Ctrl-C to come out
Upvotes: 0
Views: 75
Reputation: 58244
Your gets
call is superfluous because the STDIN.read.split("\n").each do |a|
already reads the inputs into a
. So remove the gets
:
STDIN.read.split("\n").each do |a|
if a.to_i >= 0
puts "#{a} is positive"
end
end
Note that the I/O is buffered, and you're operating on a block basis, so you'll get:
Enter these inputs:
5
4
3
Press Ctrl-D to end the input (for Linux) or Ctrl-Z (for Windows), then you'll get results:
5 is positive
4 is positive
3 is positive
=> ["5", "4", "3"]
If you want this to be more interactive, then don't use the STDIN... each
construct, but just do a loop with gets.to_i
. For example:
loop do
a = gets
break if a.nil? # Exit loop on EOF (ctrl-D)
if a.to_i > 0
puts "a is positive"
end
end
If I put this into a file, say foo.rb
, then I get:
OS_Prompt> ruby foo.rb
3
a is positive
5
a is positive
2
a is positive
-1
-3
2
a is positive
[ctrl-D]
OS_Prompt>
And it will quit the loop on ctrl-D since that will cause gets
to return nil
. Although in Windows, it might want Ctrl-Z.
Upvotes: 3
Reputation: 3946
STDIN.read.split("\n").each do |a|
This line is already taking input continuously then whats the need of gets.
while(true)
b= gets.chomp.to_i
puts b >=0 ? "b is positive" : "b is negative"
end
Here chomp is used to remove \n
from the input
Upvotes: 0
Reputation: 121000
▶ loop do
▷ b = STDIN.gets.to_i
▷ break if b.zero?
▷ puts b > 0 ? 'positive' : 'negative'
▷ end
#⇒ 5
# positive
# -4
# negative
# 0
# => nil
Upvotes: 0