将值添加到现有键值对 ruby 哈希

Add a value to an existing Key value pair ruby hash

我的 ruby 脚本过滤日志并生成这样的散列

scores = {"Rahul" => "273", "John"=> "202", "coventry" => "194"}

通过跳过一个键的多个值,这很明显

日志文件将是这样的

Rahul has 273 Rahul has 217 John has 202 Coventry has 194

是否可以生成这样的东西

scores = {"Rahul" => "273", "Rahul" =>"217",
          "John"=> "202", "coventry" => "194"}

scores = {"Rahul" => "273","217",
          "John"=> "202", "coventry" => "194"}

有没有办法强制写入哈希,即使密钥已经存在于哈希中

如有任何帮助或建议,我将不胜感激

"Rahul has 273 Rahul has 217 John has 202 Coventry has 194".
  scan(/(\w+) has (\d+)/).group_by(&:shift)
#⇒ {"Rahul"=>[["273"], ["217"]],
#   "John"=>[["202"]],
#   "Coventry"=>[["194"]]}

对于扁平化的值,请查看下面 Johan Wentholt 的评论。

要存储你的分数,你可以创建一个散列,它有一个空数组作为它的默认值:

scores = Hash.new { |hash, key| hash[key] = [] }

scores['Rahul'] #=> [] <- a fresh and empty array

您现在可以从日志中提取值并将其添加到相应键的值中。我正在使用 scan with a block: (using the pattern from )

log = 'Rahul has 273 Rahul has 217 John has 202 Coventry has 194'

log.scan(/(\w+) has (\d+)/) { |name, score| scores[name] << score.to_i }

scores #=> {"Rahul"=>[273, 217], "John"=>[202], "Coventry"=>[194]}

虽然不是必需的,但我已将每个分数转换为整数,然后再将其添加到数组中。