Monthly Archives: August 2008

You’re just in a giant Object.class_eval block

>> Object.methods.size
=> 85
>> def i_is_in_ur_Object; "kthxbai" end
=> nil
>> Object.methods.size
=> 86
>> String.new.i_is_in_ur_Object
=> "kthxbai"

Careful what you put in there!

2 Comments

Filed under ruby

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.

1 Comment

Filed under ruby