Ruby enums in C

J

Joe Van Dyk

Each instance of Joe has a MOOD which can be HAPPY, SAD, or NEUTRAL.

The Joe class is written in C. In C, what's the appropriate way for
setting MOOD to one of the appropriate values?

Thanks,
An instantiated Joe object
 
E

Eric Hodel

Each instance of Joe has a MOOD which can be HAPPY, SAD, or NEUTRAL.

The Joe class is written in C. In C, what's the appropriate way for
setting MOOD to one of the appropriate values?

rb_iv_set(joe, "@mood", rb_intern("sad"));
 
E

Eric Hodel

Is there much difference between using a C constant for that, and
using a Ruby instance variable (like how Mr. Hodel did)?

A C constant takes more work to expose to Ruby. You have to map that
opaque integer into something sensible, and then you have uglier code.

#define JOE_SAD -1
#define JOE_NEUTRAL 0
#define JOE_HAPPY 1

/* ... */
rb_define_const(cJoe, "HAPPY", INT2FIX(JOE_HAPPY));

if Joe.state == Joe::HAPPY then ... end

A Symbol in an instance variable gives you zero extra work, allows
for easier debugging on the Ruby side and gives you prettier code.

if Joe.state == :happy then ... end
 

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
474,219
Messages
2,571,120
Members
47,741
Latest member
WilliamsFo

Latest Threads

Top