Search code examples
rubyinput

How can I take multiple inputs from the same line?


I can't figure out how to take multiple inputs from one line. Here is an example:

p=gets.chomp().to_i
q=gets.chomp().to_i
puts"#{p} #{q}"

When I run this and take inputs, I have to take it from a new line. E.g.,

3
4
output:
3 4

If I type

3 4

it is not taking 4 as input and is waiting for another input from the next line. What should be done?


Solution

  • gets reads in the whole line. If you want to process multiple elements from it, you need to split on that line, or perform regex matches on it, etc. In your case:

    p, q = gets.split.map(&:to_i)
    

    BTW, in your code, the chomp calls are superfluous, since to_i will work correctly whether the string ends with a newline or not.