# Adding to Hashes

**URL:** <https://www.ruby-forum.com/t/adding-to-hashes/84211>\
**Category:** Ruby\
**Created:** [February 2, 2007, 11:57am UTC](https://www.ruby-forum.com/t/adding-to-hashes/84211 "2007-02-02T11:57:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nicken](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/d07c76/32.png) [@nicken](https://www.ruby-forum.com/u/nicken)\
**Post date:** [February 2, 2007, 11:57am UTC](https://www.ruby-forum.com/t/adding-to-hashes/84211/1 "2007-02-02T11:57:16Z")

</div>

Hello,

I need to add key and value pairs to a hash dynamically. I want to do  
this:

array = []  
array \<\< “hello”  
array \<\< “world”

But with k v pairs of a hash. The hash is being populated from a  
database and there is a potenitally unlimited (though realistically  
limited to less than 20) number of differnet keys, which my program  
will not know about until it talks to the database.

Can I dynamically create a hash something like this:

dbh.query(“select k, v from foo where id = #{id}”).each\_hash do |kv|

```
   k = kv['k']
   v = kv['v']

   myhash << k,v

```

end

return myhash

Thanks for the help!

---

<div class="post-metadata">

**Author:** ![nicken](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/d07c76/32.png) [@nicken](https://www.ruby-forum.com/u/nicken)\
**Post date:** [February 2, 2007, 12:05pm UTC](https://www.ruby-forum.com/t/adding-to-hashes/84211/2 "2007-02-02T12:05:17Z")

</div>

On 2/2/07, Nick B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> limited to less than 20) number of differnet keys, which my program  
> will not know about until it talks to the database.
> 
> Can I dynamically create a hash something like this:
> 
> dbh.query(“select k, v from foo where id = #{id}”).each\_hash do |kv|
> 
> ```
> k = kv['k']
> v = kv['v']
> 
> myhash << k,v
> 
> ```

Why not just  
myhash[k] = v

---

<div class="post-metadata">

**Author:** ![nicken](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/d07c76/32.png) [@nicken](https://www.ruby-forum.com/u/nicken)\
**Post date:** [February 2, 2007, 4:36pm UTC](https://www.ruby-forum.com/t/adding-to-hashes/84211/3 "2007-02-02T16:36:48Z")

</div>

Figured it out - its simple as always:

yourhash[‘key’] = value

adds to the hash (just like the book says)
