2011-12-08 11 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の配列の2番目の位置が更新されるかどうかはわかりませんでした。 – 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

関連する問題