Program

The program is the entirety of the source code worked by the compiler. The source gets parsed and compiled to an executable version of the program.

The program’s source code must be encoded in UTF-8.

Top-level scope

Features such as types, constants, macros and methods defined outside any other namespace are in the top-level scope.

  1. # Defines a method in the top-level scope
  2. def add(x, y)
  3. x + y
  4. end
  5. # Invokes the add method on the top-level scope
  6. add(1, 2) # => 3

Local variables in the top-level scope are file-local and not visible inside method bodies.

  1. x = 1
  2. def add(y)
  3. x + y # error: undefined local variable or method 'x'
  4. end
  5. add(2)

Private features are also only visible in the current file.

A double colon prefix (::) unambiguously references a namespace, constant, method or macro in the top-level scope:

  1. def baz
  2. puts "::baz"
  3. end
  4. CONST = "::CONST"
  5. module A
  6. def self.baz
  7. puts "A.baz"
  8. end
  9. # Without prefix, resolves to the method in the local scope
  10. baz
  11. # With :: prefix, resolves to the method in the top-level scope
  12. ::baz
  13. CONST = "A::Const"
  14. p! CONST # => "A::CONST"
  15. p! ::CONST # => "::CONST"
  16. end

Main code

Any expression that is neither a method, macro, constant or type definition, or in a method or macro body, is part of the main code. Main code is executed when the program starts in the order of the source file’s inclusion.

There is no need to use a special entry point for the main code (such as a main method).

  1. # This is a program that prints "Hello Crystal!"
  2. puts "Hello Crystal!"

Main code can also be inside namespaces:

  1. # This is a program that prints "Hello"
  2. class Hello
  3. # 'self' here is the Hello class
  4. puts self
  5. end