tags:

views:

294

answers:

3

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?

+7  A: 

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
or even$stdin.readline.split.map{|s| s.to_i }.inject{|p,i| p * i}or$stdin.readline.split.inject(1){|p,s| p * s.to_i}
Mike Woodhouse
A: 
array = input.split(' ')

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

Chris Doggett
+1  A: 

Or you could use String#scan:

irb> "input -1 -1 500 500".scan(/[+-]?\d+/).map { |str| str.to_i } 
#=> [-1, -1, 500, 500 ]
rampion