为什么我得到一个空白数组?

时间:2015-06-27 08:04:27

标签: ruby

当我在连续输入后尝试打印时,我得到一个空白数组。

puts "Enter the numbers you want"
arr = Array.new()
while gets
  arr.each do |x|
    arr =x.to_i
  end
end
print arr, ","

输出:

Enter the numbers you want
1
2

3
^Z
[],

我想知道这是否是使用gets的正确方法,以及在Ruby中处理连续输入的良好来源。

2 个答案:

答案 0 :(得分:1)

它是空的,因为您实际上从未向该数组添加值。试试这个:

puts "Enter the numbers you want"
arr = []

while x = gets
  arr << x.to_i          # this line adds x (input from `gets`) to the array
  puts arr.join(', ')
end

答案 1 :(得分:0)

您没有填充数组。 gets返回您输入的字符串。你忽略了它。

如果你想从用户输入填充数组,你应该有这样的东西:

puts "Enter the numbers you want"
arr = []
while input = gets
  arr << input.chomp  # strip off trailing newline
end

p arr
相关问题