Hick
Hick

Reputation: 36404

How can I take a specific number of lines of input in Ruby?

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?

Upvotes: 0

Views: 514

Answers (4)

Ryan Bigg
Ryan Bigg

Reputation: 107728

Why not use gets?

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

puts lines.sort

Upvotes: 1

Telemachus
Telemachus

Reputation: 19705

A variation on the previous answers:

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

Upvotes: 0

Demi
Demi

Reputation: 6227

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

Upvotes: 2

Pesto
Pesto

Reputation: 23880

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".

Upvotes: 6

Related Questions