Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print values from C extensions?

Every Ruby object is of type VALUE in C. How do I print it in a readable way?

Any other tips concerning debugging of Ruby C extensions are welcome.

like image 287
x-yuri Avatar asked Feb 19 '15 13:02

x-yuri


2 Answers

You can call p on Ruby objects with the C function rb_p. For example:

VALUE empty_array = rb_ary_new();
rb_p(empty_array); // prints out "[]"
like image 136
rmosolgo Avatar answered Sep 22 '22 02:09

rmosolgo


Here's what I came up with:

static void d(VALUE v) {
    ID sym_puts = rb_intern("puts");
    ID sym_inspect = rb_intern("inspect");
    rb_funcall(rb_mKernel, sym_puts, 1,
        rb_funcall(v, sym_inspect, 0));
}

Having it in a C file, you can output VALUEs like so:

VALUE v;
d(v);

I've borrowed the idea from this article.

like image 29
x-yuri Avatar answered Sep 18 '22 02:09

x-yuri