简体   繁体   English

如何在Ruby中的另一个字符串之后匹配和迭代一个字符串

[英]How to match and iterate on a string after another string in Ruby

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 . 例如,我要对abc求和1218 How do I go about this? 我该怎么办?

"abc-12\nxyz-17\nabc-18\npqr-13\n".split("\n").inject(0) do |sum, line|
  sum += line[/[\w]+(\d)+/].to_i
end
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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM