简体   繁体   English

从Ruby中的用户输入字符串中提取和多个整数?

[英]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 例如: - 输入-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? 我从键盘输入一个字符串 - 然后我该怎么办?

This prints ["5", "66", "7", "8"] if you type a line containing 5 66 7 8 (separated by any whitespace): 如果您输入包含5 66 7 8 (由任何空格分隔),则打印[“5”,“66”,“7”,“8”]:

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

Or you could use String#scan : 或者您可以使用String#scan

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

或者,如果您将它们作为命令行参数输入,只需使用ARGV数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM