The scope or lifetime of a variable is an important consideration when putting together your rails application.  Here are some hints about the scoping of certain types of variables, objects, controllers and methods.


h2. Variable Scoping

h3. Local Variables

Local variables are those variables that exist inside of a method.  The duration of life for these variables ends at the end of the method.

For example, from the console try this:

<pre><code>
def method1
a = 99   
end

=>

method1  => 99
a  => NameError: undefined local variable or method `a' for main:Object

def method2
puts a
end

=>

method2  => NameError: undefined local variable or method `a' for main:Object
        from (irb):15:in `method2'
        from (irb):17

</code></pre>

h3. Instance Variables

@ variables follow an instance.  

This means that when you create an object the instance variable would be created and would die when the object is destroyed.

For example, from the console, type:

<code><pre>

class TrialClass
   def method1
      @a = 99
   end
   def method2
      @a = 50
   end
end

object1 = TrialClass.new
object2 = TrialClass.new

object1.method1  => 99
object1.inspect  => #<TrialClass:0x359f4e8 @a=99>

object2.method2 = > 50
object2.inspect => #<TrialClass:0x359f4e8 @a=50>
object1.inspect  => #<TrialClass:0x359f4e9 @a=99>


</pre></code>

h3. Class Variables

@@ variables exist after their declaraion, forever.

This type of variable once declared will exist throughout the entire application.  You would use these variables when you are <fill in some more here>

For example:
<put an example here>

h3. Global Variables

$ variables are like @@ variables without a class.

$ (pronounced 'dollar-sign')  variables  are different from @@ variables because they <fill in some more here>

For example:
<put an example here>

(In addition, refer to the "Pickaxe Book's section on variable scope":http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UP.)

h2. Method Scoping

[To be filled]

(In addition, refer to the "Pickaxe Book's chapter on Classes and Objects":http://www.ruby-doc.org/docs/ProgrammingRuby/html/classes.html)


category: Understanding
