Topic: Instance Variables confusion

I'm not understanding instance variables entirely. If I have @username inside a class, User, and I have multiple instances of the User object, than @username can take on a different value for each instance of the class. I think I'm understanding that correctly. Now what if I took the @ off. Does that mean every instance of User will carry the same value?

Thanks for helping smile

Re: Instance Variables confusion

Close.  Without the @ sign it's a local variable, and is only accessible within the current scope, such as an if block.

If you add another @ sign, @@username, then it's a class variable and is the same for all instances.

Re: Instance Variables confusion

I'm reading that instance variables can be declared anywhere in a class, even inside methods. Coming from a Java perspective, I'm thinking that can lead to code that is hard to interpret. I'm use to declaring my variables at the top of the class. Is that the convention in Rails too?

Re: Instance Variables confusion

I'm also coming from a Java perspective, and for some reason it doesn't bother me.  What does declaring it at the top of the class give you?  To me it makes more sense to initialize the variable where it's first used.  It's definately not a Rails convention, as generally they tend to streamline things.

Re: Instance Variables confusion

You can set up attr_accessor or attr_reader for each instance variable if you want. This way it can be defined at the top of the class and you can have access to it from the outside - if you need it.

But, I'd try sticking with the Ruby convention. If you have trouble keeping track of instance variables, the class may be too big or have too many instance variables.

Oh, BTW, if you define an instance variable outside of a method it will not work as you expect because you are defining the instance variable for the Class, not the instances of the class. The instance methods will not have access to the same variable.

class Greeter
  @name = 'Joe'
  def self.greet
    puts "Hello #{@name}"
  end
  def greet
    puts "Hello #{@name}"
  end
end
Greeter.greet # prints 'Hello Joe'
Greeter.new.greet # prints 'Hello '

Last edited by ryanb (2006-08-31 10:42:56)

Railscasts - Free Ruby on Rails Screencasts

Re: Instance Variables confusion

There's also an 'attr' method that creates both the setter and getter.

Sure beats having to rely on eclipse to generate all those buggers for you eh?

Last edited by thabenksta (2006-08-31 11:15:34)