0

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

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

通过为一个明显的键跳过多个值

日志文件将是这样的

拉胡尔 273 拉胡尔 217 约翰 202 考文垂 194

是否有可能产生这样的东西

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

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

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

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

4

2 回答 2

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

于 2018-03-14T09:24:05.610 回答
1

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

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

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

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

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

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

于 2018-03-14T11:40:20.913 回答