Hick
Hick

Reputation: 36404

Extract and multiple integers from user-input string in Ruby?

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?

Upvotes: 2

Views: 2491

Answers (3)

rampion
rampion

Reputation: 89053

Or you could use String#scan:

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

Upvotes: 1

Chris Doggett
Chris Doggett

Reputation: 20757

array = input.split(' ')

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

Upvotes: 0

pts
pts

Reputation: 87271

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

Upvotes: 7

Related Questions