# Rb\_yield & rb\_hash\_each

**URL:** <https://www.ruby-forum.com/t/rb-yield-rb-hash-each/70635>\
**Category:** Ruby\
**Created:** [October 1, 2006, 6:42am UTC](https://www.ruby-forum.com/t/rb-yield-rb-hash-each/70635 "2006-10-01T06:42:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bct](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6a8cbe/32.png) [@bct](https://www.ruby-forum.com/u/bct)\
**Post date:** [October 1, 2006, 6:42am UTC](https://www.ruby-forum.com/t/rb-yield-rb-hash-each/70635/1 "2006-10-01T06:42:19Z")

</div>

Hello,

How do you use rb\_hash\_each?  
How do you pass blocks to methods using C in general?

Thank you,  
Brian T.

---

<div class="post-metadata">

**Author:** ![bct](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6a8cbe/32.png) [@bct](https://www.ruby-forum.com/u/bct)\
**Post date:** [October 1, 2006, 2:06pm UTC](https://www.ruby-forum.com/t/rb-yield-rb-hash-each/70635/2 "2006-10-01T14:06:40Z")

</div>

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 😉

Regards,  
Tilman
