Learn/Crystal/1. Hello, output
Lesson 1 of 8
Sign in

Crystal, lesson 1

Hello, output

The first thing to learn in any language is how to make the program say something. In Crystal that is puts, short for "put string". It writes a value to the screen and ends the line.

You can write the argument with or without parentheses: puts("hi") and puts "hi" do the same thing. For a single argument, most Crystal code leaves them out. Text in double quotes is a string. In Crystal, strings always use double quotes; single quotes are for a single character, like 'A'.

Several values at once

Give puts several arguments and it prints each one on its own line:

To put values inside a sentence, use interpolation: anything inside #{...} in a string is worked out and turned into text.

Staying on the same line

puts always ends the line. writes exactly what you give it and nothing more:

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

Countdown on one line

Press Ctrl Enter or Check to test your code.

print

You can also put a line break inside a string with \n.

A third printer, p, shows a value the way you would write it in code, quotes included. It is handy while you are figuring out what a value really is: p "hi" prints "hi".

Comments

A # starts a comment that runs to the end of the line. Crystal ignores it.

How a Crystal program runs

Crystal looks a lot like Ruby, but it is a compiled language. Before your program runs, the compiler reads the whole file, main.cr, checks that every value is used correctly, and turns it into a fast native program. That is why the first run takes a few seconds. Many mistakes, like calling a method that does not exist, are caught at this stage, before anything runs.

Once compiled, the program runs the top-level code of the file from the first line to the last. There is no main function to write: the file itself is the program.

Further reading

  • Crystal reference: Hello World
  • Crystal reference: Comments
  • API: top-level puts and print

Write a program that prints exactly these two lines:

The program reads no input.

A rocket launch counts down on a single line. Print this, followed by one line break:

Use print for each number (each one ends with ... , three dots and a space) and a single puts for Liftoff!. The starter uses puts everywhere, so every piece lands on its own line. Fix it.

puts "Hello, World!"
puts "Crystal runs this line second."
puts "one", "two"   # one
                    # two
puts "Total: #{40 + 2}"   # Total: 42
print "Loading"
print "..."
puts "done"        # Loading...done
# Greet the user first.
puts "Welcome!"   # comments can follow code too
Hello, World!
I am learning Crystal.
3... 2... 1... Liftoff!