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
  • 51,832
  • 12
  • 88
  • 127
Hick
  • 35,524
  • 46
  • 151
  • 243

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
  • 80,836
  • 20
  • 110
  • 183
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
  • 87,131
  • 49
  • 199
  • 315
0
array = input.split(' ')

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

Chris Doggett
  • 19,959
  • 4
  • 61
  • 86