# C extension: symbols

**URL:** <https://www.ruby-forum.com/t/c-extension-symbols/102465>\
**Category:** Ruby\
**Created:** [February 8, 2006, 6:09pm UTC](https://www.ruby-forum.com/t/c-extension-symbols/102465 "2006-02-08T18:09:12Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![pgundlach](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b9e5f3/32.png) [@pgundlach](https://www.ruby-forum.com/u/pgundlach)\
**Post date:** [February 8, 2006, 6:09pm UTC](https://www.ruby-forum.com/t/c-extension-symbols/102465/1 "2006-02-08T18:09:12Z")

</div>

Hi,

in pure ruby, I sometimes access hashes with symbols as keys:

{ :foo =\> “this”, :bar =\> “other” }

Q: How would I create this kind of hash on the c part?

OK, the hash is easy (rb\_hash\_new()). But how do I specify the key?  
When I use rb\_intern(“foo”), I get a hash like:

{ 1234 =\> “this”, 2345 =\> “other” }

Patrick

---

<div class="post-metadata">

**Author:** ![pgundlach](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b9e5f3/32.png) [@pgundlach](https://www.ruby-forum.com/u/pgundlach)\
**Post date:** [February 8, 2006, 6:34pm UTC](https://www.ruby-forum.com/t/c-extension-symbols/102465/2 "2006-02-08T18:34:02Z")

</div>

Patrick G. wrote:

> When I use rb\_intern(“foo”), I get a hash like:
> 
> { 1234 =\> “this”, 2345 =\> “other” }
> 
> Patrick

rb\_intern() returns an ID (ID type is defined in ruby.h). To convert  
it to a symbol use the ID2SYM() macro function. For example (untested  
code):  
VALUE h = rb\_hash\_new(), v = ID2SYM(rb\_intern(“foo”));  
rb\_hash\_aset(h, v, rb\_str\_new2(“bar”));  
rb\_p(h);

-Charlie

---

<div class="post-metadata">

**Author:** ![pgundlach](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b9e5f3/32.png) [@pgundlach](https://www.ruby-forum.com/u/pgundlach)\
**Post date:** [February 8, 2006, 6:38pm UTC](https://www.ruby-forum.com/t/c-extension-symbols/102465/3 "2006-02-08T18:38:42Z")

</div>

Hello Charlie,

> VALUE h = rb\_hash\_new(), v = ID2SYM(rb\_intern(“foo”));  
> rb\_hash\_aset(h, v, rb\_str\_new2(“bar”));  
> rb\_p(h);

thanks for ID2SYM, works like a charm. Is that documented somewhere?

Patrick

---

<div class="post-metadata">

**Author:** ![pgundlach](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b9e5f3/32.png) [@pgundlach](https://www.ruby-forum.com/u/pgundlach)\
**Post date:** [February 8, 2006, 8:03pm UTC](https://www.ruby-forum.com/t/c-extension-symbols/102465/4 "2006-02-08T20:03:43Z")

</div>

A lot of the C extension API is undocumented. If you’re going to be  
creating extensions you’ll probably find it’s worth your time to look  
at the external declarations and macros in ruby.h and intern.h, and  
then looking at the code in the Ruby iterpreter itself. I’ve found that  
the best way to find out how to use the API is to look at the code for  
the builtin classes like Array and String.
