# Ruby hash confusion

**URL:** <https://www.ruby-forum.com/t/ruby-hash-confusion/144967>\
**Category:** Rails\
**Created:** [August 4, 2008, 7:46pm UTC](https://www.ruby-forum.com/t/ruby-hash-confusion/144967 "2008-08-04T19:46:58Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [August 4, 2008, 7:46pm UTC](https://www.ruby-forum.com/t/ruby-hash-confusion/144967/1 "2008-08-04T19:46:58Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [August 4, 2008, 7:59pm UTC](https://www.ruby-forum.com/t/ruby-hash-confusion/144967/2 "2008-08-04T19:59:51Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [August 4, 2008, 8:01pm UTC](https://www.ruby-forum.com/t/ruby-hash-confusion/144967/3 "2008-08-04T20:01:39Z")

</div>

2008/8/4 Me [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> 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

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [August 4, 2008, 8:14pm UTC](https://www.ruby-forum.com/t/ruby-hash-confusion/144967/4 "2008-08-04T20:14:31Z")

</div>

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.” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
