On Thursday 28 July 2005 23:59, Mark Volkmann wrote:
> On 7/25/05, Daniel Brockman <daniel / brockman.se> wrote:
> > An expression that looks like 'identifier = value' always
> > sets a variable, and never calls a method.  This is simply
> > the way the language is defined.
> >
> > When you want to call a setter method on the current object,
> > you *have* to say 'self.foo = bar', precisely because if you
> > leave out the 'self.', you will just create a local variable.
>
> I just want to make sure I fully understand this.
>
> Isn't the preferred way of doing this the following?
>
> @foo = bar
>
> Is this equivalent to
>
> self.foo = bar
>
> Is this true?

Often it has the same effect.

> An expression that looks like '@attr-name = value' always calls a
> method whose name is 'attr-name='.

No it's the other way round. Most methods looking like 'attr_name='
are implemented like this:

    # public accessor method
    def attr_name=(val)
        # Set instance variable @attr_name
        # @attr_name is only accessible in methods of self
        @attr_name = val
    end

Let's look at an example:

    % cat foo.rb
    class Foo
        def initialize
           @text = ""
        end
        def text=(val)
            # an empty string is a "true value" in Ruby,
            # nil is a "false value"
            @text = val || ""
        end
        def text
            # just return @text
            @text
        end
        def set_nil
            @text = nil
        end
    end

    a = Foo.new
    a.text = nil
    b = Foo.new
    b.set_nil
    p a.text
    p b.text
    % ruby foo.rb
    ""
    nil

-- 
Stefan