Crystal · Lesson 1 · On the house

Hello, Crystal: run, build, interpolate

Write a .cr file, run it with crystal run, build a native binary, and print values with puts, print, p and #{} interpolation. Lesson 1 is free — on the house.

Lessons · Crystal · Lesson 1 of 10 · On the house

Hello, Crystal: run, build, interpolate

Write a .cr file, run it with crystal run, build a native binary, and print values with puts, print, p and #{} interpolation.

Illustration for Crystal
Lesson 1 is on the house.

Crystal is a statically typed language with Ruby-like syntax that compiles to native machine code through LLVM. You rarely write types, because the compiler infers them across the whole program, but every value still has a fixed type checked before the program runs.

Source files end in .cr. crystal run hello.cr compiles to a temporary binary and runs it at once. crystal build hello.cr writes a native executable named hello; add --release for full optimisation (slower to compile, much faster to run).

A program needs no main function: top-level statements run from the top of the file down. # starts a comment that runs to the end of the line.

puts prints its arguments, each followed by a newline. print prints without adding a newline. p prints the inspected form, so p "hi" shows the quotes and is handy for debugging.

Inside double-quoted strings, #{expr} evaluates any expression and inserts its to_s result. Single quotes are not strings in Crystal: 'C' is a Char.

crystal init app myapp scaffolds a project with a shard.yml (dependencies), src/ and spec/. shards install fetches dependencies, crystal spec runs tests and crystal tool format formats code.

hello.cr

# hello.cr
name = "Crystal"
major = 1
puts "Hello, #{name}!"
puts "Version #{major}.0 shipped in 2021"
puts "Two plus two is #{2 + 2}"
print "no newline yet", "\n"
p name
p 'C'
Match this when you type.

Quiz

What does crystal run hello.cr do?

Quiz

Which flag makes crystal build produce a fully optimised binary?

Quiz

What does p "hi" print?

Quiz

What is 'C' in Crystal?

Check

Match the still for: Hello, Crystal: run, build, interpolate.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.