Variables

Local Variables

These are the most common type of variables, and are declared by assigned a value to an identifier.

a = 4 // A variable is born

// two more variables
name = "Brian"
age = 24

Variables defined outside a function can be accessed anywhere, except inside functions.

Variables defined inside a function can be accessed anywhere within that function. The one exception to this is with blocks, variables which are defined only within the block are local to within the block. If you define a variable outside of a block, then it can be accessed and altered from within the block.

Global $Variables

Global variables can be accessed anywhere, inside or outside of a function, and are defined using the $ symbol.

$a = 0

def f()
    $a = $a+1
end

f()

All global variables must have a value assigned to them somewhere in your code. Using a variable which is never assigned to is a compile time error.

Accessing a global which has not yet been assigned to will cause a runtime error.

Field @Variables

Finally there you can also have variables in classes. These cannot be accessed from outside of a class, or by a sub-class (they are private).

They are denoted using the @ symbol, and are created by setting a value to them.

class Location
    def new(x, y)
        @x = x
        @y = y
    end
end

They are explained further in the Fields section, under Classes.

See also

Literals - Fields and Accessors