0
a = [[5, 6], [6, 5], [7, 4], [1, 0, 0], [9, 9], [6, 8], [8, 6], [1, 8, 0], [9, 0]]

How can I sum the integers inside the inner array and return an array of sum of the inner array?

I need it to return [(5+6), (6+5), (7+4), (1+0+0), ...], thus [11, 11, 11, 1, 18, 14, 14, 9, 9]

2
  • When asking, we expect to see evidence of your effort toward solving the problem. It looks like you're asking us to write the code for you, which is not what we do. Please read "How to Ask", including the linked pages, and "minimal reproducible example". Commented Jul 12, 2016 at 0:03
  • @theTinMan definitely! I did all my scratch work on repl.it for almost a good hour, but later I closed the page so I could not show the codes I have tried. I will do so next time. Thanks for the heads up! Commented Jul 12, 2016 at 0:19

3 Answers 3

5
a.map{|a| a.inject(:+)}
# => [11, 11, 11, 1, 18, 14, 14, 9, 9]
Sign up to request clarification or add additional context in comments.

1 Comment

You're a ninja. Beat me by 18 seconds because my response was too short
5

Try

sum_arry = a.map { |sub_arry| sub_arry.inject(&:+) }

Then sum_arry should be the array you want.

Comments

4

Use map + reduce

a.map { |a| a.reduce(:+) }

3 Comments

If all one can usefully say as an answer to a question is 29 characters or less, is the question really worth answering?
I personally thought it was a pretty good question. Answers are good if they can be less than 30 chars. Just my opinion
Any other interesting ways to do this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.