Skip to content

Crystal Cheatsheet

Ruby-like syntax with C-like performance, statically typed and compiled.

01

Getting Started

Hello World

Crystal syntax is very similar to Ruby.

crystal
puts "Hello, World!"

Variables

Variables are immutable by default in Crystal.

crystal
x = 10          # immutable
y = 20
puts x + y

Functions

No explicit return needed; last expression is returned.

crystal
def add(a, b)
  a + b
end

puts add(3, 4)

Run & Build

crystal build produces a native binary.

crystal
# crystal run main.cr
# crystal build main.cr --release
02

Types & Data Structures

Basic Types

Crystal infers types at compile time.

crystal
i = 1           # Int32
f = 3.14        # Float64
s = "hello"     # String
b = true        # Bool
a = [1, 2, 3]   # Array(Int32)

Hash

Hash is the equivalent of Ruby's Hash.

crystal
h = {"a" => 1, "b" => 2}
puts h["a"]
h["c"] = 3

Tuple

Tuples are fixed-size, mixed-type arrays.

crystal
t = {1, "hello", true}
puts t[0]
puts t[1]

Named Tuple

Named tuples use symbols as keys.

crystal
nt = {x: 1, y: 2}
puts nt[:x]
puts nt[:y]
03

Control Flow

If-Else

Ruby-style if-elsif-else.

crystal
n = 5
if n > 3
  puts "big"
elsif n == 3
  puts "three"
else
  puts "small"
end

Case

case/when for pattern matching.

crystal
day = "Mon"
case day
when "Mon" then puts "Monday"
when "Tue" then puts "Tuesday"
else puts "Other"
end

Blocks

Blocks are closures passed to methods.

crystal
[1, 2, 3].each do |n|
  puts n
end

[1, 2, 3].map { |n| n * 2 }

Was this helpful?