I understand that local variables are limited to the scope they were declared in and instance variables exist as long as the class exists, but what happens if you declare a local variable in the class scope without prefixing it with @? Doesn't that implicitly it is an instance variable, even though you didn't use an @ to declare it as one?
-
2"instance variables exist as long as the class exists" I guess you mean as long as object existsTolik Kukul– Tolik Kukul2012-12-17 17:49:50 +00:00Commented Dec 17, 2012 at 17:49
-
Yes, I did. That was a mistake. I know the difference between class and instance variables.David– David2012-12-17 19:16:20 +00:00Commented Dec 17, 2012 at 19:16
2 Answers
instance variables exist as long as the class exists
They exist as long as the object exist. Instance variables are per-object, not per-class.
what happens if you declare a local variable in the class scope without prefixing it with @?
Then the variable is in scope within the class definition, but not within any defs inside that class definition as those introduce a new scope.
Doesn't that implicitly make it an instance variable, even though you didn't use an @ to declare it as one?
No.
If you use define_method instead of def to create methods, the local variable will be accessible within the methods, but since the variable only exists once (not once per object), they'd act more like class variables than instance variables in that case. I also can't think of a good reason why you'd use them that way.
Comments
Using @makes it an instance variable for an object that you create. When you are doing things with that object you can set local variables but they disappear after use. Instance variables will stay around as long as there is an object.