Search code examples
rubyvariable-assignmentattr-accessor

how does the assignment symbol work - Ruby


In Ruby if i just assign a local variable.

sound = "bang". 

is that a main.sound=("bang") method? if so, where and how is that method "sound=" being defined? or how is that assignment working? if not, what is actually happening?

i know that for a setter method you would say x.sound=("bang"). and you are calling the method "sound=" on the object "x" with the argument "bang". and you are creating an instance variable "sound".

and i can picture all of that. but not when you assign a variable in the "main" object. as far as i know it isn't an instance variable of the Object class... or is it? I'm so confused.


Solution

  • In most programming languages, Ruby included, assignment is a strange beast. It is not a method or function, what it does is associate a name (also called an lvalue since it's left of the assignment) with a value.

    Ruby adds the ability to define methods with names ending in = that can be invoked using the assignment syntax.

    Attribute accessors are just methods that create other methods that fetch and assign member variables of the class.

    So basically there are 3 ways you see assignment:

    • the primitive = operator
    • methods with names ending in =
    • methods generated for you by the attribute accessor (these are methods ending in =)