The Class and Module love story

In Ruby, Class is a Module which, like any object, has a class.

>> Class.superclass
=> Module
>> Module.class
=> Class

But the crazy thing is, it's the complete opposite in the implementation.
(Excerpt from ruby.h)

typedef struct {
    VALUE super;
    struct st_table *iv_tbl;
} rb_classext_t;

struct RClass {
    struct RBasic basic;
    rb_classext_t *ptr;
    struct st_table *m_tbl;
    struct st_table *iv_index_tbl;
};
#define RCLASS_IV_TBL(c) (RCLASS(c)->ptr->iv_tbl)
#define RCLASS_M_TBL(c) (RCLASS(c)->m_tbl)
#define RCLASS_SUPER(c) (RCLASS(c)->ptr->super)
#define RCLASS_IV_INDEX_TBL(c) (RCLASS(c)->iv_index_tbl)
#define RMODULE_IV_TBL(m) RCLASS_IV_TBL(m)
#define RMODULE_M_TBL(m) RCLASS_M_TBL(m)
#define RMODULE_SUPER(m) RCLASS_SUPER(m)

We see it gets the instance variable table (RMODULE_IV_TBL) just like it's a class. Modules are stored in RClass structs.

I know. I'm totally confused too.

About these ads

1 Comment

Filed under ruby

One response to “The Class and Module love story

  1. I read the C code you’ve posted as saying that modules and classes are the same thing. Makes no difference which is defined first – this is all preprocessor stuff and is expanded before the compiler ever sees it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s