Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby read 2 integers at the same time

I have two integers on a line in STDIN which I would like to read at the same time. I tried pattern matching like this:

[a, b] = gets.split.map(&:to_i)

However, this failed:

solution.rb:7: syntax error, unexpected '=', expecting keyword_end
    [a, b] = gets.split.map(&:to_i)

How can I read two integers from the same line(preferably but not necessarily at the same time)?

like image 998
octavian Avatar asked Feb 08 '23 06:02

octavian


2 Answers

You need to remove brackets on the left side:

a, b = gets.split.map(&:to_i)
like image 82
falsetru Avatar answered Feb 13 '23 21:02

falsetru


It's better to be a safe side by using splat operator

a, b, * = gets.split.map(&:to_i)

for more info about splat operator, I've written a blog on Ruby Splat operator

like image 25
Gupta Avatar answered Feb 13 '23 21:02

Gupta