简体   繁体   English

更新 ruby 中特定键的值

[英]Update the value of a specific key in ruby

I am a fresher in ruby language.我是 ruby 语言的新手。 Help me to this帮我解决这个问题

I have a map, containing 4 keys.我有一个 map,包含 4 个键。 Initial state the value of all keys are zero like below初始 state 所有键的值都为零,如下所示

data_source_map = = Hash.new
data_source_map.store("ab",0)
data_source_map.store("cde",0)
data_source_map.store("fgh",0)
data_source_map.store("jik",0)

I have a while loop, iterating a files from a specific location我有一个while循环,从特定位置迭代文件

while (file = queue.deq)
  begin
    cat = 'cat'
    
    if file.split('.').last=='gz' || file.split('.').last=='zip'
      cat = 'zcat'
    end
            
    user_ids.each do |user|
      res = run_command4("aws s3 cp #{file} - | #{cat} | grep #{user} | wc -l",true,'s3cmd stream failed')
      output = "#{user},#{file.split('/')[-1]},#{file.split('/')[-2]},#{res[:output][0]}"
              
      if "ab".eql?(file.split('/')[-2])
        data_source ="ab"         
      elsif  "cde".eql?(file.split('/')[-2])
        data_source ="cde"
      elsif "fgh".eql?(file.split('/')[-2])
        data_source ="fgh"
      elsif "jik".eql?(file.split('/')[-2])
        data_source ="jik"
      else
        data_source ="NA"
      end
    end
  end
end

{res[:output][0] is a number with respect to the keys.Each file having these keys and an integer number. {res[:output][0] 是与键相关的数字。每个文件都有这些键和 integer 编号。

Each iteration i need to update the integer value of a given key.每次迭代我都需要更新给定键的 integer 值。 how to do this in ruby.如何在 ruby 中执行此操作。 am trying to create consolidated report like below我正在尝试创建如下所示的综合报告

|ab  |200
|cde |4000
|fgh |0

I suggest using a Hash with a default value so you don't need to initialize all possible keys before you start, but that is not required.我建议使用具有默认值的 Hash,这样您就不需要在开始之前初始化所有可能的键,但这不是必需的。

data_source_map = Hash.new(0)

To update a value in a hash, you just need to set the new updated value to the hash, it will overwrite the old value.要更新 hash 中的值,只需将新更新的值设置为 hash,它将覆盖旧值。

data_source_map[data_source] = data_source_map[data_source] + 1

This takes the current value from the hash and adds 1 to it, then stores it back into the Hash.这会从 hash 中获取当前值并将其加 1,然后将其存储回 Hash。 Though this is a very common operation, so there is a shorthand for it as well.虽然这是一个非常常见的操作,但它也有一个简写形式。

data_source_map[data_source] += 1

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

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