-1

Assuming I have an array like this,

a = [[1, 2], [1, 4], [1, 8], [1, 16]]

how do I convert the above into the following in Ruby?

a = [3, 5, 9, 17]

Thx in advance!

J.Yan
  • 55
  • 2
  • 8
  • 2
    Please show the code that you have tried so far **in your question**. Thank you. – Timur Shtatland Sep 13 '20 at 15:02
  • 1
    Sorry, I am just a beginner. Couldnt really wrap my head around that, so that's why I asked. – J.Yan Sep 13 '20 at 15:06
  • What is the code you are having trouble with? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Please, provide a [mre]. Please be aware that [so] is not a code-writing service, you need to show your efforts! – Jörg W Mittag Sep 13 '20 at 16:14
  • 1
    https://idownvotedbecau.se/nocode/ https://idownvotedbecau.se/noattempt/ https://idownvotedbecau.se/nomcve/ – Jörg W Mittag Sep 13 '20 at 16:14
  • Yep, would be more careful and specific – J.Yan Sep 13 '20 at 16:46

2 Answers2

1

I would go with:

a = [[1, 2], [1, 4], [1, 8], [1, 16]]
a.map!(&:sum)
#=> [3, 5, 9, 17]
spickermann
  • 100,941
  • 9
  • 101
  • 131
0

Method 1:
Use map, where you add the 2 elements of the inner 2-element array. The block { ... } returns the last expression evaluated, which is x + y:

a = [[1, 2], [1, 4], [1, 8], [1, 16]]
a = a.map{ |x, y| x + y }
puts a.inspect
# [3, 5, 9, 17]

Method 2:
Use map, then sum all elements of the inner array, and return the sum:

a = [[1, 2], [1, 4], [1, 8], [1, 16]]
a = a.map{ |el| el.sum }
puts a.inspect
# [3, 5, 9, 17]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • Thank you so very much!! I just found one that looks like this: [[1,2,3],[1,1,1]].map{|a| a.inject(:+)} # => [6, 3] . Wonder how you would think of this. – J.Yan Sep 13 '20 at 14:57
  • @Jacin.Y You can slightly modify the `inject` statement you have shown, and that will work also. Feel free to post it even "as is", as something you tried, whether or not this gives the correct result. SO users like to see evidence of prior work or research. Wrong solutions are better than no solutions at all. :) – Timur Shtatland Sep 13 '20 at 15:12