Home > Software design >  How to sum third position in arrays?
How to sum third position in arrays?

Time:06-14

I have a record with arrays:

@arrays = ["41,3,4", "39,2,3"]

I want to sum the third position of each of the arrays together (4 3)

I tried:

@arrays.sum[3] 

Do I need to iterate the array first?

Thanks!

CodePudding user response:

You can give Enumerable#sum a block to tell it what to add up:

arrays.sum { |e| e.split(',')[2].to_i }

CodePudding user response:

split elements by ,, grab 3rd, convert it to integer, then sum.

arrays.inject(0) { |acc, triplet| acc  = triplet.split(/,/)[2].to_i; acc }
  •  Tags:  
  • ruby
  • Related