'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)?
Solution 1:[1]
You need to remove brackets on the left side:
a, b = gets.split.map(&:to_i)
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | falsetru |
| Solution 2 |
