2011-12-08 64 views
0

我使用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]中的values数组中的时间戳。

# 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 
+0

为什么不只是设置foo的[K] [0] = NEW_VALUE; foo [k] [1] = new_value2 – klochner

+2

显示输入/预期输出的一些示例,以便我们可以更好地理解您的问题。 –

+0

@klochner我打算试试,但我不确定是否打字foo [k] [1]会更新v的数组中的第二个位置。 – CoryDorning

回答

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

'cached = true' =>'else updateCache(line)end'和'cached'不是必需的 –

+0

@VictorMoroz:谢谢。我更新了答案。 –

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

我认为这是我想要的。现在尝试。 – CoryDorning

+0

这似乎没有更新我的散列键阵列。 – CoryDorning