Hello World in Crystal
Your first Crystal program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Crystal program.
The Code
Create a file named hello.cr:
| |
That’s it! If you know Ruby, this looks identical - and that’s by design.
Understanding the Code
puts- Prints a string to standard output followed by a newline"Hello, World!"- A String literal enclosed in double quotes- No semicolon - Crystal doesn’t require semicolons at the end of statements
- No main function - Top-level code runs automatically
Running with Docker
The easiest way to run this without installing Crystal locally:
| |
Running Locally
If you have Crystal installed:
| |
Expected Output
Hello, World!
Key Concepts
- Ruby-like syntax - Crystal intentionally mirrors Ruby’s clean, readable style
- Compiled language - Despite the scripting feel, Crystal compiles to native code
- Type inference - The compiler automatically determines types
crystal run- Compiles and runs in one step (great for development)crystal build- Creates an optimized standalone binary
A More Detailed Version
For a slightly more structured approach showing Crystal’s type system:
| |
This version demonstrates:
- Function definition - Using
defwith type annotations - Type annotations -
name : Stringand return type: String - String interpolation - Embedding values with
#{} - Type inference -
messageis automatically typed as String
Object-Oriented Approach
Crystal is fully object-oriented:
| |
Key features shown:
@name- Instance variable with shorthand initialization- Constructor -
initializemethod runs when creating instances - Classes - Full OOP support with inheritance and polymorphism
Why Crystal Stands Out
Coming from other languages, you’ll notice Crystal’s unique characteristics:
- Ruby syntax, C speed - Write beautiful code that runs fast
- Nil safety - Compiler catches null reference errors
- No runtime - Compiles to efficient native binaries
- Great error messages - Clear, helpful compiler feedback
Compile vs Run Performance
| |
The --release flag enables optimizations, producing highly efficient executables.
Next Steps
Continue to Variables and Data Types to learn about Crystal’s powerful type system, including union types, nil safety, and the balance between explicit typing and inference.
Running Today
All examples can be run using Docker:
docker pull crystallang/crystal:1.14.0