From: "David A. Black" Date: 2009-09-22T21:52:49+09:00 Subject: Re: Accessing an instance variable in another method Hi -- On Tue, 22 Sep 2009, Subashini Kumar wrote: > Hi, > I am new to Rails.I tried developing a basic quiz application.Please > help me out in my doubt.Thanks in advance > > <% CODE %> > > class QuizController < ApplicationController > > def index > # i have retrieved the first five questions from the database for > displaying the #question to user > @quiz=Quiz.find(:all,:limit=>5) > > end > > def report > > end > > # this method checks the answer and gives score > def checkanswer > # here i want to access the @quiz object which is a set of questions i > have #retreived from the database.Hot to access it? > end > > end There are two things you have to keep in mind here. The first is that every instance of a class has its own supply of instance variables: class Person def initialize(name) @name = name end def print_name puts @name end end a = Person.new("David") a.print_name # David b = Person.new("Joe") b.print_name # Joe So every time I create a new Person object, that object has a fresh "slate" of instance variables. The second thing you need to know is that in your Rails application, every request creates a new controller object. So the @quiz variable you create for the index request is not going to exist on the next request (i.e., when the person looking at the index clicks on a link and your application goes through another request/response cycle). Instance variables are "sticky", but only for the lifetime of the object. David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2)