tags:

views:

135

answers:

4

I am taking inputs in Ruby like this:

lines = STDIN.readlines.map{|x| x.strip.to_i}.sort

This takes input from the command prompt, but I want to take input a specific number of times. Suppose my number of test cases is 3, how can I stop it after 3 lines of input?

+5  A: 
lines = []
3.times do
  lines << STDIN.readline.strip.to_i
end
lines.sort


EDIT:

If you are saying that you want it to accept an arbitrary number of inputs, you have a couple options: The simplest is to first input how many lines of input you have, like this:

num_lines = STDIN.readline.strip.to_i
lines = []
num_lines.times do
  lines << STDIN.readline.strip.to_i
end
lines.sort

Or, if you don't know how many lines to expect, you have to have some way of signifying that the data is complete. For example, if you want to have an empty line mean the end of the data:

lines = []
STDIN.each_line do |line|
  line.strip!
  break if line == ''
  lines << line.to_i
end
lines.sort

By the way, when the program is paused while awaiting input, this is not called an "infinite loop". It is "blocking" or simply "waiting for input".

Pesto
it still goes in infinite loop .. i am sorry
mekasperasky
No it doesn't, I've just tested it. Perhaps you're using the phrase "infinite loop" incorrectly?
Pesto
Maybe he means this will wait indefintely if the user only puts in two or less lines of input (not from a pipe)?
rampion
@rampion: That would not be an infinite loop would it?
Geoffrey Chetwood
I just slammed my face into my desk. I am feeling incredibly dizzy and I am sure I lost a few brain cells. I am afraid I still cannot agree with your definition of an infinite loop.
TheTXI
Why not gets instead of STDIN?
Ryan Bigg
@Radar: First, it reflects the same structure as in the question. Second, I find STDIN.readline more readily apparent to a newbie than gets. But there's no real reason not to use gets instead.
Pesto
+2  A: 

One line of code...

This will take only the number of lines you want to use - the desired count is in variable @requested_count:

lines = STDIN.readlines.values_at(0..@requested_count - 1).map{|x| x.strip.to_i}.sort
Demi
A: 

A variation on the previous answers:

lines = []
1.upto(3) do
  lines << STDIN.readline.strip.to_i
end
puts lines.sort
Telemachus
+1  A: 

Why not use gets?

lines = []
1.upto(3) do
  lines << gets.to_i
end

puts lines.sort
Ryan Bigg
Cargo cult programming: I was thinking about the "get a specific number of lines" part of the problem and simply copied that part of the code from previous answers.
Telemachus