0

I'm using Ruby and have a hash, call it foo, and its value is an Array with a fixed length of 2.

How can I update one of the indexes within the hash values array? Here's an example:

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

Further clarification:

I'm looping through a file and inside I want to to see if the current line matches the hash key k. If it does I want to update the timestamp in the values array, which is stored in 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
3
  • why not just set foo[k][0] = new_value; foo[k][1] = new_value2 Commented Dec 8, 2011 at 21:13
  • 2
    Show some sample of input/expected output, so we can understand better your question. Commented Dec 8, 2011 at 21:14
  • @klochner i was going to try that, but i wasn't sure if typing foo[k][1] would update the second position in v's array. Commented Dec 8, 2011 at 21:23

2 Answers 2

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)

A better and faster solution:

if @cache.include? line
  @cache[line][1] = Time.now.utc
else
  updateCache(line)
end
Sign up to request clarification or add additional context in comments.

1 Comment

cached = true => else updateCache(line) end and cached is not required
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]}

1 Comment

i think this is what i want. trying now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.