问题
What I missing for create new array for each pair of numbers and then put the sum of each pair? Btw, is it possible to enter pair of numbers through ',' on one line?
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
The input must be like this:
2 # Number of pairs
562 -881 # First pair
310 -385 # Second pair
So the output will be:
-319
-75
回答1:
For the first part of your question you modify your code like this:
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
For the second part of your question, you can do:
a, b = gets.split(',').map(&:to_i)
and rework the calculation/output part like this (with just one loop):
puts "Here are the sums: "
arr.each { |a, b| puts a + b } # calculate and output for each
plus some error handling.
来源:https://stackoverflow.com/questions/32716100/how-to-re-create-each-time-create-new-array-in-ruby