Rb_yield & rb_hash_each

Hello,

How do you use rb_hash_each?
How do you pass blocks to methods using C in general?

Thank you,
Brian T.

Brian T. [2006-10-01 13:41]:

How do you use rb_hash_each?
How do you pass blocks to methods using C in general?

I guess you mean rb_hash_foreach()? rb_hash_each() isn’t available in
extensions, and rb_hash() just calls rb_hash_foreach() anyway.

Here’s an example:

VALUE props = create_and_populate_hash();
VALUE callback_data = …;

rb_hash_foreach (props, my_callback, callback_data);

static int
my_callback (VALUE key, VALUE value, VALUE callback_data)
{
/* meanings of the arguments should be obvious */

return ST_CONTINUE;
/* see enum st_retval for other possible return values */

}

Note that rb_hash_foreach() was only added in Ruby 1.8.4.
A better way would be to use rb_iterate and rb_each:

rb_iterate (rb_each, my_hash, my_callback, callback_data);

static VALUE
my_callback (VALUE array, VALUE callback_data)
{
/* array is [key, value] for hashes */
}

This works with any object that implements the “each” method, not just
hashes. It’s probably slower though :wink:

Regards,
Tilman