Forum: Ruby c extension: symbols

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ef5256760771d0c5cad01dc3b35382ba?d=identicon&s=25 Patrick Gundlach (Guest)
on 2006-02-08 18:09
(Received via mailing list)
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
4596f0fa753784a18ef8289341df5948?d=identicon&s=25 Charles Mills (Guest)
on 2006-02-08 18:34
(Received via mailing list)
Patrick Gundlach 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
Ef5256760771d0c5cad01dc3b35382ba?d=identicon&s=25 Patrick Gundlach (Guest)
on 2006-02-08 18:38
(Received via mailing list)
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
B33ea5c12d767bfd1253940a960274f5?d=identicon&s=25 rmagick@gmail.com (Guest)
on 2006-02-08 20:03
(Received via mailing list)
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.
This topic is locked and can not be replied to.