How to re-create (each time create new) array in Ruby?

烈酒焚心 提交于 2020-01-05 03:07:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!