using Comparable in C

T

teeler

Is there a way i can use the functions defined in compar.c (der, like
without copying them)?

I'd like to be able to arbitrarily compare VALUE's - do i just have to
imitate that code? Assuming that the underlying type has Comparable
mixed in, would I just have to do what compar.c does, something like:

cmp_ge(x, y)
VALUE x, y;
{
VALUE c = rb_funcall(x, cmp, 1, y);

if (NIL_P(c)) return cmperr();
if (rb_cmpint(c, x, y) >= 0) return Qtrue;
return Qfalse;
}

and the same for the rest (le, eq, etc.) ?
It'd be nice if i could just call cmp_ge(VALUE, VALUE) but I realize
it's not in the C api...
 
D

David Balmain

Is there a way i can use the functions defined in compar.c (der, like
without copying them)?

I'd like to be able to arbitrarily compare VALUE's - do i just have to
imitate that code? Assuming that the underlying type has Comparable
mixed in, would I just have to do what compar.c does, something like:

cmp_ge(x, y)
VALUE x, y;
{
VALUE c = rb_funcall(x, cmp, 1, y);

if (NIL_P(c)) return cmperr();
if (rb_cmpint(c, x, y) >= 0) return Qtrue;
return Qfalse;
}

and the same for the rest (le, eq, etc.) ?
It'd be nice if i could just call cmp_ge(VALUE, VALUE) but I realize
it's not in the C api...

You can just use rb_funcall;

if (RTEST(rb_funcall(object, rb_intern("=="), 1, other_object))) {
//...
}

A new thing I just learned, for single character operators like '<'
and '>' you can just do this;

if (RTEST(rb_funcall(object, '<', 1, other_object))) {
//...
}

If I was going to be doing this type of thing a lot I'd rewrite the
compar.c functions, returning int instead of VALUE. For example;

#define my_cmperr() (rb_cmperr(x, y), 0)

int
my_cmp_ge(VALUE x, VALUE y)
{
VALUE c = rb_funcall(x, cmp, 1, y);

if (NIL_P(c)) return my_cmperr();
if (rb_cmpint(c, x, y) >= 0) return 1;
return 0;
}

Just my personal opinion.

Cheers,
Dave
 
T

teeler

I figured thats what I'd have to do - i was trying to save myself the
work.

Thanks!
Tyler
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top