The Program

The program is a global object in which you can define types, methods and file-local variables.

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

A method’s value is the value of its last expression; there’s no need for explicit return expressions. However, explicit return expressions are possible:

  1. def even?(num)
  2. if num % 2 == 0
  3. return true
  4. end
  5. return false
  6. end

When invoking a method without a receiver, like add(1, 2), it will be searched for in the program if not found in the current type or any of its ancestors.

  1. def add(x, y)
  2. x + y
  3. end
  4. class Foo
  5. def bar
  6. # invokes the program's add method
  7. add(1, 2)
  8. # invokes Foo's baz method
  9. baz(1, 2)
  10. end
  11. def baz(x, y)
  12. x * y
  13. end
  14. end

If you want to invoke the program’s method, even though the current type defines a method with the same name, prefix the call with :::

  1. def baz(x, y)
  2. x + y
  3. end
  4. class Foo
  5. def bar
  6. baz(4, 2) #=> 2
  7. ::baz(4, 2) #=> 6
  8. end
  9. def baz(x, y)
  10. x - y
  11. end
  12. end

Variables declared in a program are not visible inside methods:

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

Parentheses in method invocations are optional:

  1. add 1, 2 # same as add(1, 2)

Main code

Main code, the code that is run when you compile and run a program, can be written directly in a source file without the need to put it in a special “main” method:

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

Main code can also be inside type declarations:

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