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

时间:2018-03-14 09:14:01

标签: ruby ruby-hash

我的ruby脚本过滤日志并生成像这样的哈希

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

跳过明显的键的多个值

日志文件将是这样的

  

Rahul有273 Rahul有217 John有202考文垂有194

是否可以生成类似这样的内容

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

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

即使密钥已经存在于哈希

中,也有办法强制写入哈希

我将非常感谢任何帮助或建议

2 个答案:

答案 0 :(得分:4)

"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的评论。

答案 1 :(得分:1)

要存储您的分数,您可以创建一个散列,其中包含一个空数组作为其默认值:

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

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

您现在可以从日志中提取值并将其添加到相应键的值中。我正在使用scan一个块:(使用mudasobwa's answer中的模式)

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]}

虽然不是必需的,但我在将每个分数添加到数组之前将其转换为整数。

相关问题