Satya's blog - Ruby on Rails instance variables explained

Jun 13 2009 00:23 Ruby on Rails instance variables explained

Instance variables (@foo, for example) are a Ruby concept, not Rails. But it's a little confusing in the Rails' Model-View-Controller paradigm.

Consider that in pure Ruby, an instance variable is available to an object (which is *instantiated* from a class). The instance variable can be used and changed by any methods of the object. This is unlike non-@ variables, which are limited to the scope where they're defined:

def ex1
   foo=1 # defined within the ex1 method
end

def ex2
    if @foo==1
        bar=1
    end
    bar # nil, because it's out of scope
end

def ex3
    @foo=1 # remains defined after ex3 returns
end

Now here's my point: in Rails, instance variables defined in a controller method are available to the view, but not to any models called from that method. Why?

Because a Rails view is NOT a separate class. It's a template and it's part of the current controller object. A model is a separate class.

That's all. It's a simple point, but it can be confusing at first to those not familiar with Ruby or Object Oriented Programming.

Tag: rails