# C extension: How to create a Hash entry with Symbol key?

**URL:** <https://www.ruby-forum.com/t/c-extension-how-to-create-a-hash-entry-with-symbol-key/177613>\
**Category:** Ruby\
**Created:** [October 21, 2009, 1:54am UTC](https://www.ruby-forum.com/t/c-extension-how-to-create-a-hash-entry-with-symbol-key/177613 "2009-10-21T01:54:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [October 21, 2009, 1:54am UTC](https://www.ruby-forum.com/t/c-extension-how-to-create-a-hash-entry-with-symbol-key/177613/1 "2009-10-21T01:54:59Z")

</div>

Hi, I do know how to create a hash from C in wich keys and values are  
strings:

VALUE hash = rb\_hash\_new();  
rb\_hash\_aset(hash, rb\_str\_new(“mykey”,5), rb\_str\_new2(myvalue));

But now I want to create Hash entries with Symbol keys so the resulting  
Hash  
would look like:  
{ :mykey =\> “lalala” }

By reading the C API documentation I don’t find how to do it:  
[Ruby C Extension API Documentation (Ruby 1.8) - eqqon](http://www.eqqon.com/index.php/Ruby_C_Extension)

Any help please? Thanks a lot.

---

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [October 21, 2009, 2:06am UTC](https://www.ruby-forum.com/t/c-extension-how-to-create-a-hash-entry-with-symbol-key/177613/2 "2009-10-21T02:06:42Z")

</div>

El MiÃ©rcoles, 21 de Octubre de 2009, IÃ±aki Baz C. escribiÃ³:

> Hi, I do know how to create a hash from C in wich keys and values are  
> strings:
> 
> VALUE hash = rb\_hash\_new();  
> rb\_hash\_aset(hash, rb\_str\_new(“mykey”,5), rb\_str\_new2(myvalue));
> 
> But now I want to create Hash entries with Symbol keys so the resulting  
> Hash would look like:  
> { :mykey =\> “lalala” }

ops, solved right now:

rb\_hash\_aset(hash, ID2SYM( rb\_intern(“mykey”) ),  
rb\_str\_new2(myvalue));

🙂

---

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [October 21, 2009, 4:43am UTC](https://www.ruby-forum.com/t/c-extension-how-to-create-a-hash-entry-with-symbol-key/177613/3 "2009-10-21T04:43:02Z")

</div>

On Tue, Oct 20, 2009 at 4:54 PM, IÃ±aki Baz C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> 

This should do it…

rb\_hash\_aset(hash, ID2SYM(rb\_intern(“mykey”)), rb\_str\_new2(myvalue));

John
