4 ms·
> In Ruby, every object that is instantiated is represented internally by basically three things: > * A table of instance values > * A pointer to the class of
by pansa2 2y ago
> In Ruby, every object that is instantiated is represented internally by basically three things:
> * A table of instance values
> * A pointer to the class of the object, used for method lookup
> * A pointer to a unique class for that instance, called the “singleton class” of the object, also used for method lookup
I don't think this is accurate. The source code shows a generic `RObject` [0] contains flags, a pointer to a class (named `klass`), and instance variables. An `RClass` [1] contains flags, `klass`, `super` and a table of methods.
In both cases there is only a single pointer to a class that's used for method lookup.
-
> Ruby will look in the singleton class for the specific user instance first, and will only look for an instance method of the class if there is no matching method in the singleton class.
This is true, but it implies that Ruby does two separate lookups. The way it actually works is more elegant.
An object's `klass` points to its singleton class, and method lookup happens only on that class and its superclasses. The second lookup implied above happens implicitly, because the class of the object is an ancestor of the singleton class.
Specifically, for `class C`, its `klass` points to the singleton class `<< C`, whose ancestors are `<< Object`, `<< BasicObject`, `Class`, `Module`, `Object` and `BasicObject`.
IMO Ruby's whole object model, and in particular the design of this inheritance chain, is beautiful and underappreciated.
-
> I’m not really sure why the Smalltalk solution wasn’t used
I think the way Ruby actually works is closer to the Smalltalk approach than the author realizes.
-
[0] https://github.com/ruby/ruby/blob/71f402c5d50919b0329d04704da8aa8982ab0585/include/ruby/internal/core/robject.h#L83 https://github.com/ruby/ruby/blob/71f402c5d50919b0329d04704d...
[1] https://github.com/ruby/ruby/blob/71f402c5d50919b0329d04704da8aa8982ab0585/internal/class.h#L80 https://github.com/ruby/ruby/blob/71f402c5d50919b0329d04704d...
- ryukoposting 2y agoHaving embedded MRI into a variety of side projects over the years, I can confirm your evaluation of Ruby's method lookup procedure is accurate, at least in the context of that legacy, reference implementation of the language. I also agree that Ruby's design is deeply underappreciated.