Greetings! In this episode, we will introduce Crystal, a statically-typed and
compiled language, learn how to install it, compile, and run a simple program.
So, first of all, what is Crystal? Crystal is a language with a syntax heavily
inspired by Ruby, with a focus on programmer happiness. Even if Crystal can
compile some simple Ruby programs, keep in mind that it is an entirely
compiled language, making it much faster and with a lower memory footprint.
Under the hood, it uses LLVM for compiling to native code.
Crystal is also statically typed, which means that the compiler will help you
catch type errors in compile-time. But more on this later: let's now dive
into installing Crystal.
We will install Crystal in Mac OS using
homebrew, but as you can see, there
are also instructions for Debian, CentOS, and other Linux distributions.
brew install crystal-lang
Installing Crystal on Mac is as easy as installing the
package. After installation, we can test that it installed successfully.
We’ll write a simple
hello world program.
puts "Hello world"
Now run it by passing the file to the command
$ crystal hello.cr
Under the hood, this is compiling our program to a binary and running it. We can
do each of those steps separately. First let us compile the program:
$ crystal build hello.cr
$ file hello
As we can see, there is a hello executable.
And then we can run it:
This binary already has all of its required dependencies embedded, so we can
easily copy it to any other machine with the same architecture and run it there,
making deployment a very easy task.
Speaking of deployment, we can also compile our program in release mode, which
takes longer to compile, but enables several optimisations that greatly increase
its speed in runtime for production:
crystal build --release hello.cr
Now, since we are working with a very small program, we won't notice any
differences. Let’s set up the scaffolding for a larger project:
crystal init app hello
This will create the basic structure for a full-blown project, with an already
initialised git repository, license and readme files. It also comes with stubs
for tests, and the
shard.yml for describing the project and managing
dependencies, also known as shards.
As a quick example, let’s add the faker shard, which generates random names.
Note that Crystal does not have a centralized repository, like rubygems or npm.
The way to specify a dependency is through its git repository, which in this
case sits in Github.
We install the dependencies listed running
Now we can require the library and use it from our code.
And if we run our project...
...it prints out a random name.
So, now that you know how to install Crystal, and create and run your first
project, in the next episode, we will get started with the language basics. See