Skip to main content

Hello World (first programs) · Beginner · 15 min

Hello World in Crystal: Ruby-like syntax, compiled with LLVM

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Crystal 1.22.3 · crystallang/crystal:1.22.3 image

You will install Crystal 1.22, run Hello World with crystal run, build an optimised native binary with crystal build --release, handle the nil that gets can return, and start a project with crystal init and shards.

On this page

Crystal looks like Ruby and runs like C. A Crystal file reads almost exactly like a Ruby script: puts, blocks, def ... end, string interpolation with #{}. But there is no interpreter. The crystal compiler checks the types of the whole program, hands it to LLVM (the same optimiser behind Clang and Rust) and produces a native executable.

The part that surprises Ruby developers is that you almost never write a type, yet every value has one, fixed at compile time. Crystal works the types out from how you use them. If a value might be nil, the compiler knows that too and will not build a program that calls a method on it without checking first. You will see that happen in this tutorial.

You will install Crystal 1.22.3, run Hello World, build an optimised binary, read a name from the keyboard safely, and create a project with crystal init. Everything happens in a throwaway folder, ~/hello-crystal, which you delete at the end.

Step 1 · Install Crystal 1.22.3

On Ubuntu, Debian and Fedora, the Crystal team's install script adds their package repository and installs the crystal package, which includes shards, the dependency manager:

Bash
curl -fsSL https://crystal-lang.org/install.sh | sudo bash

Piping a script into sudo bash runs it as root. If you prefer to read it first, open https://crystal-lang.org/install.sh in your browser before running the command. Because Crystal comes from an apt repository, sudo apt update && sudo apt upgrade keeps it up to date from now on.

On macOS, use Homebrew:

Bash
brew install crystal

On Windows, Crystal is a preview: the official install page says it is largely usable but not complete. For this tutorial, use WSL with Ubuntu and follow the Ubuntu command.

The packages pull in LLVM libraries and a C toolchain, so the download is larger than the compiler alone. If you are on prepaid mobile data, run it on Wi-Fi.

Check the version:

Bash
crystal --version

Check it worked

The first line reads Crystal 1.22.3 followed by a build date, and a later line names the LLVM version Crystal was built with. A newer 1.22 patch release is fine. command not found means the install did not finish; run the install command again and read its last lines for an error.

Step 2 · Write hello.cr and run it

Make the demo folder and create the source file:

Bash
mkdir -p ~/hello-crystal
cd ~/hello-crystal
cat > hello.cr <<'CR'
puts "Hello, world!"
CR

You can also type that one line into your editor and save it as hello.cr in ~/hello-crystal. Here is all there is to it:

  • puts writes its argument followed by a newline. It is a method from Crystal's standard library, available everywhere without an import.
  • "Hello, world!" is a String. Crystal strings are UTF-8 and always use double quotes; single quotes make a Char, one character, such as 'a'.
  • There is no main function. Code at the top level of the file runs from top to bottom when the program starts, as in Ruby or Python.

Run it:

Bash
cd ~/hello-crystal
crystal run hello.cr

crystal run compiles the program into Crystal's cache folder, runs the result and leaves no file in your folder. crystal hello.cr is a shorter way to write the same command.

Check it worked

The terminal prints Hello, world! after a pause of a second or two. That pause is the compiler at work: even this one line is compiled together with the parts of the standard library it uses. If you see Error: file 'hello.cr' not found, you are not in ~/hello-crystal; run cd ~/hello-crystal and try again.

Step 3 · See type inference at work

Write a second file that asks the compiler what types it has worked out:

Bash
cd ~/hello-crystal
cat > types.cr <<'CR'
name = "Ada"
count = 3
price = 2.5

puts typeof(name)
puts typeof(count)
puts typeof(price)
puts name * count
CR
crystal run types.cr
  • name = "Ada" declares a variable. No type is written, but from now on the compiler knows name is a String.
  • count = 3 is an Int32, a 32-bit whole number, Crystal's default for integer literals.
  • price = 2.5 is a Float64.
  • typeof(...) asks the compiler for the type of an expression. It is answered while compiling, not while running.
  • name * count repeats a string, as in Ruby.

Now make a mistake Ruby would only find when that line ran. Add a line that adds a number to a string:

Bash
cd ~/hello-crystal
echo 'puts count + name' >> types.cr
crystal run types.cr

Crystal refuses to build the program. The error points at the new line and says something like expected argument #1 to 'Int32#+' to be ... not String, then lists the types Int32#+ does accept. Notice that none of the earlier puts lines ran: the whole program is checked before any of it runs. Remove the bad line before you carry on:

Bash
cd ~/hello-crystal
head -n 8 types.cr > types.tmp && mv types.tmp types.cr
crystal run types.cr

Check it worked

The first run printed String, Int32, Float64 and AdaAdaAda, one per line. The run with count + name printed a compile error naming Int32#+ and nothing else. After removing that line, the program prints the four lines again.

Step 4 · Build a release binary and time it

crystal run is for trying things. crystal build writes an executable you keep, and --release turns on LLVM's full optimisations. Write a small program that does real work, a recursive Fibonacci calculation:

Bash
cd ~/hello-crystal
cat > fib.cr <<'CR'
def fib(n : Int32) : Int32
  n < 2 ? n : fib(n - 1) + fib(n - 2)
end

puts fib(32)
CR
crystal build --release fib.cr
ls -lh fib
time ./fib
  • def fib(n : Int32) : Int32 defines a method. Here the types are written out: n : Int32 says the argument must be an Int32, and the : Int32 after the brackets is the return type. Type annotations are optional in Crystal, but on methods they document intent and give clearer errors.
  • n < 2 ? n : fib(n - 1) + fib(n - 2) returns n for 0 and 1, otherwise the sum of the two previous Fibonacci numbers. The last expression in a method is its return value, so there is no return.
  • crystal build --release fib.cr writes an executable called fib, named after the source file. A release build takes noticeably longer to compile than crystal run, because LLVM is optimising.
  • time ./fib runs it and reports how long it took.

If Ruby is installed (see Hello World in Ruby), run the same algorithm there to compare:

Bash
cd ~/hello-crystal
cat > fib.rb <<'RB'
def fib(n)
  n < 2 ? n : fib(n - 1) + fib(n - 2)
end

puts fib(32)
RB
time ruby fib.rb

The Ruby file is the Crystal file minus the two type annotations. That closeness is Crystal's main selling point: the code looks the same, but one is compiled ahead of time to machine code and the other is run by an interpreter. On a typical laptop the Crystal binary finishes in a small fraction of the Ruby time; your exact numbers depend on the machine.

Crystal also checks integer arithmetic for you. If a sum does not fit in an Int32 (its largest value is 2,147,483,647), the program stops with an Arithmetic overflow error instead of quietly printing a wrong number. For larger results, use Int64 in both annotations.

Check it worked

ls -lh fib shows an executable file in your folder. ./fib prints 2178309, and time reports a real time, typically well under a second. If you ran the Ruby version, it printed the same number and took longer.

Step 5 · Read a name and handle nil

gets reads one line from the keyboard. It returns a String, or nil when there is no more input, for example when the reader presses Ctrl+D or input comes from an empty file. Its type is String?, which is short for String | Nil. Write the obvious version first:

Bash
cd ~/hello-crystal
cat > greet.cr <<'CR'
print "What is your name? "
name = gets
puts "Hello, #{name.strip}!"
CR
crystal run greet.cr

The compiler stops with undefined method 'strip' for Nil (compile-time type is (String | Nil)). It knows name might be nil, and nil has no strip method. In Ruby this mistake shows up as a NoMethodError the first time someone presses Ctrl+D; in Crystal the program does not build until you deal with it.

Replace the file with a version that checks:

Bash
cd ~/hello-crystal
cat > greet.cr <<'CR'
print "What is your name? "
input = gets

if input
  name = input.strip
  name = "world" if name.empty?
  puts "Hello, #{name}!"
else
  puts
  puts "No input. Hello, world!"
end
CR
  • print writes text without a newline, so the reader types on the same line as the question.
  • input = gets stores the line. gets already removes the newline at the end.
  • if input is true for any String and false for nil. Inside the if branch the compiler narrows the type of input to String, so input.strip compiles. This is called flow typing.
  • name = "world" if name.empty? is a trailing if: it replaces an empty answer with a default.
  • "Hello, #{name}!" inserts the value of name into the string.
  • The else branch runs when gets returned nil. The bare puts prints an empty line, so the message does not land after the question.

Run it and type your name:

Bash
cd ~/hello-crystal
crystal run greet.cr

Then try it with input from a pipe, and with no input at all:

Bash
cd ~/hello-crystal
echo "Adébáyọ̀" | crystal run greet.cr
crystal run greet.cr < /dev/null

Names with accents and tone marks, such as Yoruba or Igbo names, print correctly because Crystal strings are UTF-8. "Adébáyọ̀".size counts characters (Unicode code points), and .bytesize counts bytes, which is larger for any non-ASCII text.

Check it worked

The first version would not compile and named Nil in the error. The fixed version prints What is your name? Hello, Adébáyọ̀! from the pipe, and No input. Hello, world! (on its own line) when reading from /dev/null. Typing your name at the prompt greets you by name; pressing Enter on an empty line greets the world.

Step 6 · Start a project with crystal init and shards

Single files are fine for experiments. A real program gets a project folder with a shard.yml, which names the program, lists its dependencies and says what to build. crystal init app creates one:

Bash
cd ~/hello-crystal
crystal init app greeter
ls -A greeter
cat greeter/shard.yml
  • app makes an application skeleton; lib would make a library for others to use.
  • greeter is the folder and the project name. Names must be lower case and may use letters, digits, - and _.
  • If Git is installed, crystal init also runs git init and fills in the author from your Git settings. If Git has no user.name set, or Git is not installed, you get your-name-here placeholders; edit them in shard.yml and LICENSE.

The targets section of shard.yml says that the program greeter is built from src/greeter.cr. Open that file: it holds a Greeter module with a VERSION constant and a TODO comment, and does nothing yet. Replace it with a program that uses the version:

Bash
cd ~/hello-crystal/greeter
cat > src/greeter.cr <<'CR'
module Greeter
  VERSION = "0.1.0"

  def self.greet(name : String) : String
    "Hello, #{name}!"
  end
end

puts Greeter.greet(ARGV.first? || "world")
puts "greeter #{Greeter::VERSION}"
CR
shards build
ls bin
./bin/greeter
./bin/greeter Ada
  • module Greeter ... end groups related code under one name, so it does not clash with code from libraries.
  • def self.greet defines a method on the module itself, called as Greeter.greet.
  • ARGV holds the command-line arguments as an Array(String). ARGV.first? returns the first one, or nil if there is none (methods ending in ? that may return nil are a Crystal convention), and || "world" supplies the default. The compiler accepts this because the result of || here is always a String.
  • Greeter::VERSION reads the constant from inside the module.
  • shards build installs any dependencies listed in shard.yml (there are none yet) and compiles each target into the bin folder. Add --release for an optimised build.

Libraries in Crystal are called shards. You add one under a dependencies: key in shard.yml, pointing at its Git repository, and shards install fetches it into a lib folder. That is how you would add Kemal, a small web framework, when you build a web service.

Check it worked

ls -A greeter lists shard.yml, src, spec, README.md, LICENSE, .gitignore and .editorconfig (plus .git if Git is installed). ls bin shows greeter. ./bin/greeter prints Hello, world! then greeter 0.1.0, and ./bin/greeter Ada prints Hello, Ada! first.

Step 7 · Common mistakes, where Crystal is used, and clean up

Errors beginners hit most often:

  • Single quotes for text. puts 'Hello' fails with an error about a character literal, because '...' holds exactly one Char. Use double quotes for strings.
  • Calling a method on something that might be nil. undefined method '...' for Nil means a value has type Something | Nil. Check it with if value, or supply a default with ||, as you did with gets and ARGV.first?.
  • Expecting Ruby's dynamic tricks. Crystal has no eval, and you cannot add methods to a class while the program is running. Crystal's macros, which run at compile time, cover many of the same needs.
  • Long compile times on big programs. Crystal compiles the whole program every time, so builds grow with the code base. Use crystal run or plain crystal build while developing and keep --release for the build you ship.

Where Crystal is used: web services and APIs, with frameworks such as Kemal and Lucky; command-line tools that should start instantly and ship as one executable; and projects such as Invidious, an alternative YouTube front end. The Crystal compiler itself is written in Crystal. Release binaries start fast and use little memory, which suits a small, low-cost VPS.

When you are finished, delete the demo folder:

Bash
cd ~
rm -rf ~/hello-crystal

Keep Crystal installed if you are carrying on. To remove it later on Ubuntu, run sudo apt remove crystal; on macOS, brew uninstall crystal.

Check it worked

ls ~/hello-crystal reports No such file or directory, and crystal --version still prints Crystal 1.22.3 if you kept the compiler.

Next steps

  • See the language Crystal borrowed its syntax from, and how an interpreter changes the workflow: Hello World in Ruby.
  • Try another compiled language with Python-like syntax and type inference: Hello World in Nim.
  • Compare Crystal's binaries with Go's single static binary and cross-compiling: Hello World in Go.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.