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!
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!
I would go with:
a = [[1, 2], [1, 4], [1, 8], [1, 16]]
a.map!(&:sum)
#=> [3, 5, 9, 17]
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]