2

I want to take multiple integer inputs in same line

eg :- input -1 -1 500 500

so that I can multiply them. I am taking the input in a string from keyboard - then what should I do?

Mike Woodhouse
  • 50,507
  • 12
  • 87
  • 126
Hick
  • 33,822
  • 46
  • 145
  • 240

3 Answers3

7

This prints ["5", "66", "7", "8"] if you type a line containing 5 66 7 8 (separated by any whitespace):

p $stdin.readline.split

To get them multiplied, do something like this:

q = 1
$stdin.readline.split.each {|n| q *= n.to_i }
p q
pts
  • 71,941
  • 19
  • 102
  • 171
1

Or you could use String#scan:

irb> "input -1 -1 500 500".scan(/[+-]?\d+/).map { |str| str.to_i } 
#=> [-1, -1, 500, 500 ]
rampion
  • 84,670
  • 47
  • 191
  • 309
0
array = input.split(' ')

or, if you're entering them as command line parameters, just use the ARGV array

Chris Doggett
  • 18,871
  • 4
  • 59
  • 86