开发者

Splitting string to integer from single-line user input?

开发者 https://www.devze.com 2023-02-01 05:59 出处:网络
I just started learning some ruby, and I want to do something like this: print \"Insert two numbers: \"

I just started learning some ruby, and I want to do something like this:

print "Insert two numbers: "
a, b = gets.split(" ")

but I want to make a and b to be integers at the same time (in the same line).. If I add .to_i to the second line (before or after split(" ")), it doesn't work... so, how should I approach this? mapping, splitting, slicing? ok, I know I开发者_JAVA百科 could use scanf, but other than scanf, how would I do this?

sorry for such a noobish question, but I just couldn't find a good enough answer only googling...


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

Or more universal:

a, b = gets.scan(/\-?\d+/).map(&:to_i)


a , b = gets.split.map { |num| num.to_i }

This should work

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号