Reputation: 41
In the books I'm reading, I always see
def initialize (side_length)
@side_length = side_length
end
If the object variable always equals the variable with the same name why not write the language to just equal it without having to type it out?
For example:
def initialize (side_length)
@side_length # this could just equal side_length without stating it
end
That way we don't have to type it over with over.
Upvotes: 4
Views: 151
Reputation: 4226
In the example given:
def initialize(side_length)
@side_length = side_length
end
The @side_length = side_length
is just an assignment, passing the available argument to an instance variable, in this case it happens to be the same name as the argument.
However those two values don't have to have same names - it's usually named that way for readability/convention reasons. That same code could just as easily be:
def initialize(side_length)
@muffin = side_length
end
The above code is perfectly fine, it just wouldn't read as well (and might slightly confuse someone giving it a first glance). Here's another example of the argument not being assigned to an instance variable of the same name.
It would be possible to write the language in a way which assumes that the argument variable should automatically be assigned to an instance variable of the same name, but that would mean more logic for handling arguments, and that same assumption may result in more restrictions for the developer, for example, someone who may actually want to assign side_length
to @muffin
for whatever reason.
Here's a SO question similar to this one - the accepted answer provides an interesting solution.
Hope this helps!
Upvotes: 1
Reputation: 168199
It is because "the object variable [does not] always [equal] the variable withthe [sic] same name".
Upvotes: 0