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


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, key| hash[key] = {} }     and the hash assignment to:       $output_hash[key][port_num] = status


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