2

I have a string like:

"abc-12\nxyz-17\nabc-18\npqr-13\n"

I want to match the number after each string and sum them all up. For example, I want to sum 12 and 18 for abc. How do I go about this?

2 Answers 2

2
s = "abc-12\nxyz-17\nabc-18\npqr-13\n"

s.split.inject(Hash.new(0)) { |h,e| id, n = e.split('-'); h[id] += n.to_i; h }
=> {"abc"=>30, "xyz"=>17, "pqr"=>13}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a Ruby Idiom to convert the generated hash to two arrays. I want to get ["abc", "xyz", "pqr"] and [30, 17, 13]. I ended up writing a method for this.
@navgeet - Hash has methods named keys and values. Those give you the arrays you need respectively.
2
"abc-12\nxyz-17\nabc-18\npqr-13\n".split("\n").inject(0) do |sum, line|
  sum += line[/[\w]+(\d)+/].to_i
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.