What is Crystal
Crystal is like Ruby but compiled, with types, and speed.
What you can make with Crystal
- Fast webapps that look and feel like Ruby
- Fast Ruby extensions
- LISP implementations and your own languages
- CLI Apps
How to get Crystal
On macOS run:
$ brew install crystal-lang
On Ubuntu run:
$ curl https://dist.crystal-lang.org/apt/setup.sh | sudo bash $ sudo apt-get install crystal
On Arch run:
$ sudo pacman -S crystal
How to make things with Crystal
First things first, let's run some code. Run the following to open a crystal playground:
$ crystal play
How to make Hello World with Crystal
Open it up and type out some code:
puts "Hello world!"
Tip: Strings in Crystal are always double quoted.
Everything in Crystal is an object:
# Strings are objects "hello world".class #=> String Class # Numbers are objects 1.class #=> Int32 Class # Special values are objects nil.class #=> Nil Class true.class #=> Bool Class false.class #=> Bool Class
Because everything is an object we get methods on every thing:
1.to_s #=> "1" ["cats", "dogs"].join(" ") #=> "cats dogs": String
How to make a Webapp With Crystal
We outputted a string, so now let's output that string on an http port, like a real developer.
First create a new Crystal project:
$ crystal init app cats_are_awesome $ cd cats_are_awesome
Add Kemal (a Sinatra like web framework) to shard.yaml
dependencies: kemal: github: kemalcr/kemal branch: master
Now install Kemal using shards:
$ shards install
Once it finishes we can finish our app declaring the awesomeness of cats. Open
src/cats_are_awesome.cr and change it to the following:
require "kemal" get "/" do "Cats are awesome!" end Kemal.run
Now you can run it like this:
$ crystal build --release src/cats_are_awesome.cr $ ./cats_are_awesome
Congrats you are now a Crystal programmer! I knew you could do it! I believed in you!