C extension: How to get a block passed to a method?

Hi, let’s imagine the following Ruby code:

my_method(“hello”) {
puts “bye”
}

In pure Ruby the method definition would be:

def my_method string, &block
  puts string
  block.call
end

Now the question is: how to do the same at Ruby C level? I assume the
following will not work:

rb_define_module_function(mModule, “my_method”, my_method, 2);

since:

method(:my_method).arity
=> 1

So how can I get the block given to a method in C code?

Thanks a lot.

On Wed, Apr 18, 2012 at 12:34 PM, Iaki Baz C. [email protected]
wrote:

If I understand your question correctly, you’re asking how to invoke a
block that’s passed into a method written as a native extension. Is
that correct?

In a Ruby extension written in C, you would use something like this:

// if a block was passed to this method then invoke it
if(rb_block_given_p())
{
rb_yield(/* args */);
}

rb_block_given_p() returns true if a code block was passed into the
method being processed. And rb_yield invokes that block with the
provided arguments (you can pass 0 or more args to the rb_yield).

HTH.

2012/4/18 Darryl L. Pierce [email protected]:

If I understand your question correctly, you’re asking how to invoke a
block that’s passed into a method written as a native extension. Is
that correct?

Not exactly. What I need is not to execute the passed block, but to
get it as a VALUE object to store it somewhere in my C code and so.

to get it as a VALUE use
rb_block_proc()

On Wed, Apr 18, 2012 at 7:34 PM, Iñaki Baz C. [email protected]
wrote:

So how can I get the block given to a method in C code?

If rb_block_given_p returns true you can use rb_block_proc to get the
VALUE for the proc.

HTH,
Ammar

2012/4/18 Ammar A. [email protected]:

On Wed, Apr 18, 2012 at 7:34 PM, Iñaki Baz C. [email protected] wrote:

So how can I get the block given to a method in C code?

If rb_block_given_p returns true you can use rb_block_proc to get the
VALUE for the proc.

Thanks a lot!