Ruby hash confusion

I have a hash:
$output_hash={}

I have a loop where “key” will remain the same while port_num
increments.

$output_hash[key] = {port_num => status}

I only get the last item when I do a $output_hash.inspect. “status”
is a variable.

Um, if that’s the code you’re running then yeah, you’re only going to
get the last value of port_num used. You’re constantly overwriting
what’s in $output_hash[key].

$output_hash[key] ||= {}
$output_hash[key][port_num] = status

Jason

2008/8/4 Me [email protected]:

is a variable.
Well, that’s how hash tables are supposed to work. What should
the output_hash contain after the loop?

I’m taking two wild guesses at what you need:

  1. Change the line to:
    $output_hash[port_num] = status

  2. Initialize $output_hash like this:
    $output_hash = Hash.new { |hash, key| hash[key] = {} }
    and the hash assignment to:
    $output_hash[key][port_num] = status

Stefan

That worked, Awesome. I keep forgetting how to initialize a multi
level hash. Perl is much easier to work with hashes in some senses.

On Aug 4, 1:00 pm, “Stefan L.” [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs