Ruby, how to read user input in scanf-style, as in C ++

I am new to Ruby. I need to read from user input numbers (n), and in C ++ I used this code

for(i=0;i<N;i++) { scanf("%d",&array[i]); } 

this code reads exactly (n) numbers separated by any spaces (tabs, spaces, newlines).

How can I do this in ruby?

in Ruby, I tried to do it like this:

 require 'scanf' n = scanf("%d"); arr = Array.new() n.times { arr << scanf("%d") } 

but this code does not work when I install the line as follows:

 1 4 8 

but works fine if I introduce this

 1 4 8 
+6
source share
2 answers

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

+4
source

Use String # scan

I am not 100% sure that I know what you really want to do here. If you just want to scan a string for numbers, you can use String # scan to do something like this:

 digits = '1 4 8'.scan /\d+/ # => ["1", "4", "8"] 

This will return the array of numbers found in the string, and you can access the array of numbers using Array or Enumerable , which you like.

If you want to handle newlines, as well as tabs or spaces, all you have to do is add the m flag for multi-line matching. For instance:

 digits = '1 4 8'.scan /\d+/m # => ["1", "4", "8"] 
+4
source

All Articles