Joel VanderWerf
6/14/2005 12:33:00 AM
Lowell Kirsh wrote:
> I'm wondering about the difference between writing something like
>
> @x = ...
> and
> self.x = ...
>
> from within a class. Are they the same thing? To be more concrete, I
> have given a fuller example below:
They are different, but the degree of difference depends on the context.
The "@x =" construct is ruby's built-in way of assigning to an instance
variable in the current object ("self"). It does not invoke any methods.
The "self.x =" construct is a special syntax for calling the method
whose name is "x=" on the object denoted by "self". This method may or
may not assign to the instance variable @x, and it may do other things
in addition to assigning to @x. For instance, you might also execute
some debugging code:
class Foo
def x=(val)
puts "setting x = #{val.inspect}"
@x = val
end
end
Or you might not assign to @x at all. For example:
class Square
def width=(val)
self.height = val
end
def height=(val)
@height = val
end
end
Since width and height must be equal, there's no need to store them
separately. But users of the Square class don't have to know that. Some
people call this the "uniform access principle".