It's a common mistake made by Java coders coming to Ruby as well, and one of the big conceptual jumps I had to get my head around. At first it seems odd, but it's really one of the cooler aspects of Ruby -- all code is executable, including class definitions.
So, instance variables must be declared inside methods. It has to do with how 'self' is evaluated. 'self' is the current object. The interpreter will lookup method calls and variable references first in 'self':
class Fish
@var = "foo" # here 'self' == Fish, the constant which contains the class object
def foo
# do foo
end
end
fish = Fish.new
fish.foo # here 'self' == fish, an instance of Fish
In a class definition, 'self' is set to be the class object being defined, so any references within a class definition will refer to that class object, in this case Fish.
When a method is called on an instance of Fish, however, self is set to be the receiver of the call, the particular instance of Fish. So outside of a method definition, self is the class object. Inside a method, self is the instance of the receiver. This is why @var outside of a method definition is more like a static variable in Java, and @var inside a method definition is an instance variable.