0

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
  • 2
    "instance variables exist as long as the class exists" I guess you mean as long as object exists Commented Dec 17, 2012 at 17:49
  • Yes, I did. That was a mistake. I know the difference between class and instance variables. Commented Dec 17, 2012 at 19:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

"they disappear after use"? What exactly do you mean by "after use" here? Surely you can use a local variable more than once, no?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.