From: Phrogz Date: 2009-03-31T05:10:02+09:00 Subject: Re: When to use instance variables @ On Mar 30, 1:52 pm, Steve Dogers wrote: > Hi, I have a couple questions about instance variables in Ruby. > 1) do i need to declare them at the top of my class file - I do > understand the accessors are automatic but I'm not sure if I can just > pull a @product in the middle of a function No. You can ask for any instance variable at any time - if no value has ever been set, you will get nil back. You can set any instance variable at any time. A common idiom is: @foo ||= 42 which is the same as "@foo = @foo || 42" which technically means "Set @foo to 42 if is it currently false or nil"; when you're not dealing with an instance variable that deals in boolean values, however, it basically means "Set @foo to 42 unless I already set it to some value." > 2) do i need to use the @ to refer to them in the class. Would it work > without the @, and if so, how does it differentiate them from local > vars? It does not work without the @. You must use it everywhere, even when using something like: variable_name = "foo" instance_variable_set( :"@#{variable_name}", 42 ) > 3) I've seen code where just below the class declaration, objects are > instantiated like product = Product.new - I don't see a @ sign, does > that mean it's a local var? How can a local var even exist at the class > level, outside a function? Class 'declarations' aren't quite what you think they are. They're actually code that is executed. Try this on for size: msg = "outside" puts "#{msg} class" class Foo msg = "inside" puts "#{msg} class" end puts "#{msg} class" Note in particular the last message; the output "outside class" lets you know that there are two local variables with the same name, in their own scopes.