Home > Back-end >  How to sum up third elements of string in array
How to sum up third elements of string in array

Time:07-12

I have the following output:

["1154,1,8.00", "1162,1,8.00", "1161,1,8.00"]

I would like to sum the third element of each item: 8.00 8.00 8.00

I've tried with .last, .map with no luck.

What is the best way of doing this?

CodePudding user response:

You can do it like this:

["1154,1,8.00", "1162,1,8.00", "1161,1,8.00"].sum { |x| x.split(',').last.to_f }

# output
# => 24.0

CodePudding user response:

arr = ["1154,1,8.00", "1162,1,8.00", "1161,1,8.00"]
rgx = /(?<=,)(?:0|[1-9]\d*)\.\d{2}\z/
arr.sum { |s| s[rgx].to_f }
  #=> 24.0

The regular expression can be broken down as follows.

/
(?<=,)    # positive lookbehind asserts previous character is ','
(?:       # begin non-capture group
  0       # match '0'
  |       # or
  [1-9]   # match a digit other than '0'
  \d*     # match zero or more digits
)         # end non-capture group
\.        # match '.'
\d{2}     # match two digits
\z        # match end of string
/
  • Related