April 12th, 2012, 11:20 PM
Quick Question from a newb
I'm writing a piece of AI code as a means to learn Ruby. I'm getting confused on some syntactical choices that don't seem to make a differece (yet.)
So here are a flurry of questions:
-When defining a global variable; do you use the '@' sign? Why or why not? I.E. somevar vs. @somevar
It seems I don't need to, but it feels wrong to have variables that have different symbols in front of them
-When defining class variables; do you use '@', '@@', or just the name? Why? It seems '@' is the appropriate way to go but various websites show people do it different ways.
-Would this be the proper way to copy identity's value into a variable? Again, it seems to work in the code but it may be inefficient, deprecated syntax or something else.
Thank you for helping a newb on a crash course
p = piece.new.value
April 24th, 2012, 01:22 PM
Global variables are prefixed with a dollar sign. So $foo would be a global variable. @foo is an instance variable and foo without a prefix is a local variable. You use a local variable if you only need the variable within the current scope. You use an instance variable when you need the variable to be accessible from anywhere within the current object. You use global variables when... Well, preferably you don't use global variables.
Originally Posted by tescrin
I've explained when to use instance variables above. Variables that start with @@ are class variables (also known as static variables in other languages). You use class variables when you need the variable to have the same value for all objects of the same class.
I don't know what it means to "copy identity's value into a variable", but the code you've shown doesn't do anything useful at all. First of all it contains a syntax error (missing "end" in initialize). Then even if you fix that the class really doesn't do anything. If you create it, you set @value to 0 and it will stay 0 as long as the object exists. Then you can call value to get the value of @value. So basically you can create Piece objects and make them tell you that their value is 0.