4

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.

vgoff
  • 10,980
  • 3
  • 38
  • 56
  • Where would `@side_length` be expected to get its value from? This is an initialize method. Also, if you are seeing this written commonly, do realize that there (for good reason) should be no space between the opening parenthesis and the method name. – vgoff Jun 12 '15 at 09:00

2 Answers2

1

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!

Community
  • 1
  • 1
Zoran
  • 4,196
  • 2
  • 22
  • 33
  • I thought of that and knew it could be differant. It could have been if you leave out the equal variable it uses the initialize variable or you could put in the equal variable if you want it different. – Stacy Proficy Jun 12 '15 at 03:41
  • 1
    That would introduce an exceptional syntax into the language, and violate the principle of least surprise. There is no logical reason why `@side_length` would be an assignment, instead of evaluating to its value like it normally does. – Amadan Jun 12 '15 at 04:25
0

It is because "the object variable [does not] always [equal] the variable withthe [sic] same name".

sawa
  • 165,429
  • 45
  • 277
  • 381