Accessing a hash value by string or symbol in C

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