In Ruby, we assign values to objects with the = operator.
Combine this with implicit typing and we frequently get situations like this:
myVar= :asymbol
The above line both creates a new symbol object, and binds the object to the variable name myVar.
Semantically, how is this done?
I have had it hammered into my head that the = operator is not magic syntax built into the interpreter, but is actually just syntactic sugar for the object.=(value) method.
With this in mind, my best guess is that when the interpreter sees we are trying to assign a value to an undefined variable name, it first creates a new object of some special type, like undefined or null or something, and then passes the := message to that object with the payload being the value we are trying to assign.
However, calling .class on an un-instantiated object just throws an exception because Ruby thinks we're trying to call a method (whose name is the name of the variable that you're trying to bring into existence) on self
> obj.class
> NameError: undefined variable or method 'obj' for main:Object
So, as far as I can tell, I have no way of figuring this out experimentally.
Side note:
In the case of symbol assignment, I believe that the value assigned ( A.K.A. the value returned by the instantiated object's object_id method, A.K.A. the value of the unsigned long VALUE variable on the C level) is a number that represents an offset in a table somewhere (I believe this is how Ruby achieves 'immediate value' for symbol objects).
In other cases, the value may be a direct encoding of the object itself, or a value that is meant to be cast to a pointer in reference to a struct.
Regardless, the way that Ruby represents the object and whether we end up assigning a reference or the object itself is not what I am asking about here.
Additional question:
What class is the = method inherited from? I can't find it in the spec for Object or BasicObject.
=method.=operator, where as mine is about its implementation in Ruby.