如何将单行输入拆分为不同数据类型的多个变量。
3 2 3 1
n = 3 #Integer/FixNum
a = [2,3,1] #Array
动态获得a(输入)的3(n)次
像,
ip -> 5 1 3 4 5 6
op -> n = 5 and a = [1,3,4,5,6]
ip -> 7 1 2 3 4 5 6 7
op -> n = 7 and a = [1,2,3,4,5,6,7]
a,b = gets.split(" ").map(&:to_i) #it didn't not work
op -> a = 1, b = 2
答案 0 :(得分:3)
您可以使用splat运算符:
array = gets.split.map(&:to_i)
#=> [7, 1, 2, 3, 4, 5, 6, 7]
a, *b = array # <===== magic happens here
a #=> 7
b #=> [1, 2, 3, 4, 5, 6, 7]
答案 1 :(得分:2)
b = gets.chomp.split(" ").map(&:to_i)
# => [7, 1, 2, 3, 4, 5, 6, 7]
a = b.shift
# => 7
b
# => [1, 2, 3, 4, 5, 6, 7]