# Insert dynamic values into a hash

**URL:** <https://www.ruby-forum.com/t/insert-dynamic-values-into-a-hash/144552>\
**Category:** Rails\
**Created:** [July 30, 2008, 9:07pm UTC](https://www.ruby-forum.com/t/insert-dynamic-values-into-a-hash/144552 "2008-07-30T21:07:58Z")\
**Posts on this page:** 3\
**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:** [July 30, 2008, 9:07pm UTC](https://www.ruby-forum.com/t/insert-dynamic-values-into-a-hash/144552/1 "2008-07-30T21:07:58Z")

</div>

I have a loop that I am trying to put key values pairs into a hash  
from. There are 6 rows of data,  
when I do a outputHash.inspect all I get is the last value. Where do  
the other values go or what I am I doing wrong?  
row.each {|line|  
line =~ /^\s\*\d+\s\*\S+\s\*\S+\s\*(\d+)\s\*\D+(\d+)/  
port\_num = $1  
if $1  
status = $2 =~ /0/ ? “Available” : “Not Available”  
outputHash = {port\_num =\> status}  
}  
outputHash.inspect

---

<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:** [July 31, 2008, 9:54am UTC](https://www.ruby-forum.com/t/insert-dynamic-values-into-a-hash/144552/2 "2008-07-31T09:54:51Z")

</div>

On Tue, Jul 29, 2008 at 10:04 PM, Me [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> outputHash = {port_num => status
> 
> ```

You are overwriting outputHash here.

You probably want outputHash[port\_num] = status

---

<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:** [July 31, 2008, 12:47pm UTC](https://www.ruby-forum.com/t/insert-dynamic-values-into-a-hash/144552/3 "2008-07-31T12:47:01Z")

</div>

On 30 Jul 2008, at 04:04, Me wrote:

> ```
> outputHash = {port_num => status}
> 
> ```
> 
> }  
> outputHash.inspect

outputHash = {port\_num =\> status}

This creates a new hash each time. You want outputHash[port\_num]=status  
(and the variable needs to exist before the block (becaused of scoping)

Fred
