Difference instance variable @ or self

First: I’m new to Ruby

Simple model:

class Product < ActiveRecord::Base

def save
STDERR << "save: " << @name << “\n”
STDERR << "save: " << self.name << “\n”
end
end

I thought that both lines should give the same result…

I’m pretty new to Ruby myself, I’ve kinda learned as required so I’m
patchy.

From what I’ve seen however, I think ‘self’ is relative to the current
scope, i.e instance or class. Where as @ is always in instance scope.

Ian.

self is the object itself.

self.name is saying that there’s a public method on self to be called
(attr_reader :name)

@name says ‘get the instance variable @name for this class instance’

Use ‘self’ pretty much the same way you’d use ‘this’ in Java or C++,
though
not in the cases that you can use @ (passing yourself to another method
is
the most used example).

Jason

Hi –

On Mon, 28 Aug 2006, Jason R. wrote:

From what I’ve seen however, I think ‘self’ is relative to the current
scope, i.e instance or class. Where as @ is always in instance scope.

self is the “default object”. There’s always one and only one self at
any point in a Ruby program.

Since classes are objects, self can be a class:

class SelfTest
p self
end # => output: SelfTest

Instance variables are a way for individual objects (including Class
objects) to store information and maintain state. Every object has
its own instance variables.

There’s a tight connection between instance variables and self:
whenever you see @var, @name, etc., you’re seeing an instance variable
that belongs to self.

self is the object itself.

self.name is saying that there’s a public method on self to be called
(attr_reader :name)

All it really says is that you’re sending the message ‘name’ to the
object self. Usually you do that in cases where there’s a
corresponding method – but not always.

attr_reader isn’t connected to this; there are many methods you can
call on objects that aren’t created with attr-reader.

@name says ‘get the instance variable @name for this class instance’

More precisely: @name is the instance variable @name belonging to
self (whatever self is at that given moment in runtime).

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org