Accessing a hash value by string or symbol in C

D

Daniel Berger

I think the issue of string vs symbol hash access came up recently.
Here's a function I use I thought I'd share for C extension writers:

/* Example:
*
* # Equivalent to hash['alpha'] || hash[:alpha]
* rb_hash_aref2(v_hash, "alpha")
*
* Returns nil if neither is found.
*/
static VALUE rb_hash_aref2(VALUE v_hash, char* key){
VALUE v_key, v_val;

v_key = rb_str_new2(key);
v_val = rb_hash_aref(v_hash, v_key);

if(NIL_P(v_val))
v_val = rb_hash_aref(v_hash, ID2SYM(rb_intern(key)));

return v_val;
}

Regards,

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top