Variable types in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2008-03-21 17:59:36 - Graham EllisIn Ruby:
* Variable with names starting with a lower case letter are local variables
* Names starting with a capital letter are constants - you can set them once each time you run a program and then they are fixed
* Names starting with a single @ character are object variables - in other words, you'll usually create one of each of the @ variables in an object for each object of the class you create. (I say "usually" as Ruby is dynamic and you can add variable to an object long after you have run the constructor if you really want to!)
* Names starting with two @ characters are class variables - so you create just one for the whole class which is shared between all instances.
* Names starting with a $ are global variables which you can refer to anywhere in your code.
You do NOT declare whether a variable is an int, a float or a scaly_anteater in Ruby, as all variables contain objects - and indeed a variable may contain a string at one point in your program, a cube at a later point and can finish up as a puff_of_smoke.
Here's an example piece of code.
def initialize(diameter,colour="white")
@diam = diameter
@colour = colour
@@ndisc += 1
$ticker += 1
tocker = 17
end
This is a constructor for an object for which who object variables are created - @colour and @diam. There is also a class variable called @@ndisc which is incremented every time this constructor is run, And $ticker is a global variable - it can be reference anywhere else in the code. The bare variables diameter, colour and tocker are local - and the tocker variable appears to be pointless (Ruby won't complain) as it is set then wasted as the method exits.
See a complete example that uses this code here