Ruby Quiz (Intermediate) #5

question mark

Question

Say you have this simple home-made (and not very useful) class:

Write some code in order to prove that instance methods are defined in the singleton class of an instance, and that class methods are defined in the class’ metaclass (the singleton class for a class).

 

Solution

All we need is a way to get to the singleton class, so we’ll open the Object class:

 

And then it’s simply a matter of listing the instance methods in each of the singleton classes:

 

which will produce this output:

SimpleClass' class methods:
allocate
my_class_method
superclass
new

SimpleClass' instance methods:
my_instance_method

If you liked the drift, you might as well be interested by why’s metaid gem.

Advertisements

Got a comment?

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

%d bloggers like this: