[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: rb_yield & rb_hash_each

Tilman Sauerbeck

10/1/2006 12:05:00 PM

Brian Takita [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 ;)

Regards,
Tilman

--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?