如何在Ruby中重新创建(每次创建新的)数组?
我错过了为每对数字创建新数组然后把每一对的总和? 顺便说一句,是否有可能通过’,’在一行输入一对数字?
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
对于问题的第一部分,您可以像这样修改代码:
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
加上一些error handling。