Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
12
18
abc
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}
Add a comment
Hash
keys
values
"abc-12\nxyz-17\nabc-18\npqr-13\n".split("\n").inject(0) do |sum, line| sum += line[/[\w]+(\d)+/].to_i end
Required, but never shown
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.
Explore related questions
See similar questions with these tags.