Skip to content

Variables and Constants

Variables are declared by assignment. Types are inferred by default:

name = "Alice" # String, inferred
age = 30 # Int, inferred

Explicit type annotations use : Type after the name:

name: String = "Alice"
count: Int = 0

Assignment to an unknown name creates a new variable in the current scope:

x = 10 # x created in local scope

Assignment to a known name reassigns the existing variable, regardless of which scope it lives in:

x = 10
if condition
x = 20 # reassigns outer x
end
puts x # 20

var explicitly introduces a new binding in the current scope, shadowing any existing variable of the same name. The outer binding is untouched:

x = 10
if condition
var x = 20 # new binding — outer x is unchanged
end
puts x # 10

var is also how a name is reused for a value of a different type further down the same method. Plain assignment cannot change a variable’s type:

input = read_line # input: String
input = input.to_int # compile error — input is a String
var input = input.to_int # new binding — input: Int from here on

Names written in ALL_CAPS are automatically treated as constants. The compiler enforces this and promotes the value to a readonly field or compile-time constant in the IL:

MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30.0
APP_NAME = "Amethyst"

Assigning a namespace or type to a PascalCase name declares an alias rather than a constant — see Aliasing.

Constants must be assigned at declaration. Reassignment is a compile error:

MAX_RETRIES = 5 # compile error — MAX_RETRIES is a constant

Constants are scoped to their enclosing namespace, class, or module. Top-level constants are accessible from anywhere.

The compiler promotes to a compile-time constant (const in IL) when the value is a literal. Otherwise it becomes a static readonly field:

MAX_SIZE = 100 # const int MAX_SIZE = 100
PREFIX = compute() # static readonly string PREFIX = compute()