2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

All is great for the first part, but output works twice, what's the issue of that?
@kirbrown: Sorry, what do you mean with "works twice"? Note that both lines a = ... and b = ... have to be replaced by the single, suggested line.
Yes, of course I replace them both. For example 2 -> Enter pair of numbers: -> 1,1 -> Enter pair of numbers: -> 1,1 -> Here are the sums: -> 2 2 -> Here are the sums: -> 2 2
So for the original program we can also delete second iteration, I think.
@kirbrown: Sorry, I don't get you. In your original program, you have two loops: one for iterating over all pairs (times), one for iterating over the two elements of each pair (each). The second one can be replace (unrolled) by sum = arr[0] + arr[1] or something like that, yes. Was this your point?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.