I have to admit in this case, I canโt make the program as compact as the C ++ version. It seems that in Ruby, scanf does not work like C ++ streams for IO streams, but for strings you need to provide a block to execute several scans per line.
So here is one solution:
a = Array.new n = gets.to_i while a.length < n gets.scanf("%d") { |d| a << d[0] } end
The only problem you get is that you ask for, for example, 3 numbers, and then the user enters 10 numbers on one line, then a will contain all these 10 numbers. To fix this, you can simply truncate the array after loop completion:
a = a.take(n)
This solution will read the digits n from the input, regardless of the space. The user can enter them all on one line or on separate lines or on a combination of both (which I assume was your initial requirement).
source share