Steve said:
Hi, I have a couple questions about instance variables in Ruby.
1) do i need to declare them at the top of my class file - I do
understand the accessors are automatic but I'm not sure if I can just
pull a @product in the middle of a function
No, you don't need to declare them at the top of your file, just before
you use them. It's good practice to initialise each of your class
variables in your constructor, but this is not always possible.
in the middle of a member function, you can just pull a '@product =
something' even if you haven't already defined it, but bugs are harder
to trace if variables start popping up all over the place.
2) do i need to use the @ to refer to them in the class. Would it work
without the @, and if so, how does it differentiate them from local
vars?
Yes, always with the @ that's exactly how their scope is known to the
interpreter.
3) I've seen code where just below the class declaration, objects are
instantiated like product = Product.new - I don't see a @ sign, does
that mean it's a local var? How can a local var even exist at the class
level, outside a function?
a local var existing at the class level outside a function? That to me
means something like this:
class Klass
product = Product.new
def some_function
nil
end
end
That doesn't make sense to me and has no accessible means (I could be
wrong on this one though). It's valid syntax, but to my understanding,
it will be instantiated and then immediately set for garbage
collection. A subtle note is that if the variable name starts with a
Capital letter, then it is a constant that belongs to that class and has
java-like public scope, so can be referred to by Klass::Constant
Also, you might see some people write code that looks procedural, but
uses @variables and so forth. This is because you are by default in the
Object class's scope. Hmmm, this makes me think that local variables at
the class level should be treated identically as the procedural-like
code at the Object scope. I think I have just confused myself, can
anyone clarify this? (Of course, I'm not actually going to use this
feature, even if it exists, but it would be nice to understand)
=======================================================================
This email, including any attachments, is only for the intended
addressee. It is subject to copyright, is confidential and may be
the subject of legal or other privilege, none of which is waived or
lost by reason of this transmission.
If the receiver is not the intended addressee, please accept our
apologies, notify us by return, delete all copies and perform no
other act on the email.
Unfortunately, we cannot warrant that the email has not been
altered or corrupted during transmission.
=======================================================================