如何更新哈希值数组?

时间:2011-12-08 21:05:32

标签: ruby arrays hash

我正在使用Ruby并使用哈希,将其称为foo,其值为固定长度为2的数组。

如何更新哈希值数组中的一个索引?这是一个例子:

foo.each do |k, v|
  if k == 'some value'
    foo[k] = update v[0]
    foo[k] = update v[1]
  end
end

进一步澄清:

我在循环浏览文件并在内部,我想查看当前行是否与散列键k匹配。如果是的话我想更新值数组中的时间戳,该数组存储在v[1]中。

# read lines  from the input file
File.open(@regfile, 'r') do |file|
  file.each_line do |line|
    # cache control
    cached = false

    # loop through @cache
    @cache.each do |k, v|
      # if (url is cached)
      if line == k
        # update the timestamp
        @cache[k] = Time.now.getutc  # need this to be put in v[1]

        # set cached to true
        cached = true
      end
    end

    # if cached go to next line
    next if cached

    # otherwise add to cache
    updateCache(line)
  end
end

2 个答案:

答案 0 :(得分:3)

# cache control
cached = false

# loop through @cache
@cache.each do |k, v|
  # if (url is cached)
  if line == k
    # update the timestamp
    @cache[k] = Time.now.getutc  # need this to be put in v[1]

    # set cached to true
    cached = true
  end
end

# if cached go to next line
next if cached

# otherwise add to cache
updateCache(line)

更好更快的解决方案:

if @cache.include? line
  @cache[line][1] = Time.now.utc
else
  updateCache(line)
end

答案 1 :(得分:2)

foo = { 'v1' => [1, 2], 'v2' => [3, 4] }

foo.each do |k, v|
  v[0] += 10
  v[1] += 10
end

p foo  # {"v1"=>[11, 12], "v2"=>[13, 14]}