如何在Ruby中重新创建(每次创建新的)数组?

时间:2015-09-22 11:49:48

标签: arrays ruby each

我缺少为每对数字创建新数组然后将每对的总和放在一起?顺便说一下,是否可以通过','在一行输入一对数字?

arr = []
sum = 0

puts "How much pair of numbers do you want to sum?"
iter = gets.to_i

iter.times do |n|
  puts "Enter pair of numbers: "
    a = gets.to_i
    b = gets.to_i
    arr << a
    arr << b
end

iter.times do |n|
  puts "Here are the sums: "
  arr.each { |x| sum += x }
  puts sum
end

输入必须如下:

2 # Number of pairs 
562 -881 # First pair
310 -385 # Second pair

所以输出将是:

-319
-75

1 个答案:

答案 0 :(得分:2)

对于问题的第一部分,您可以像这样修改代码:

arr = []
sum = 0

puts "How much pair of numbers do you want to sum?"
iter = gets.to_i

iter.times do |n|
  puts "Enter pair of numbers: "
  a = gets.to_i
  b = gets.to_i
  arr << [a, b]   # store a new 2-element array to arr
end

iter.times do |n|
  puts "Here are the sums: "
  arr.each { |a, b| puts a + b } # calculate and output for each
end

对于问题的第二部分,您可以这样做:

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

并像这样重做计算/输出部分(只有一个循环):

puts "Here are the sums: "
arr.each { |a, b| puts a + b } # calculate and output for each

加上一些错误处理。