today 5 Mar 2018
access_time 6 minutes to read
First things first, what is Crystal and why am I talking about it at a ruby meetup?
Well it’s a programming language released in 2014 that claims to be as fast as C and as slick as Ruby. Big claims right? I was pretty skeptical going in but I’ve definitely found that it delivers good speed and some very nice looking code.
Despite being so young it’s quite stable and has a strong standard library.
Before we dive too deep into it’s features lets just how similar is it to Ruby. First up, Ruby:
Now lets compare that to the equivalent Crystal code:
Notice the difference? That’s right, there is none! This bit of code is both valid Ruby and Crystal without any weird tricks or hacks.
Now lets look at a quick Kemal example. This is the Crystal equivalent of Sinatra.
That’s it! You now have an incredibly fast and lightweight web server. The benchmark on the Kemal site shows some very impressive metrics.
It’s actually really quick! Lets have a quick look at the performance of my very naive prime generator.
It’s inspired by Ruby, of course it’s beautiful.
This helps catch errors at compile time and is one of the reasons it can be as fast as it is.
Let’s have a look at a slightly more complex example. Here we define a method that can take in two different classes.
I’m not gonna lie, I haven’t had a reason to play with macros yet but they seem incredibly powerful and possibly confusing. I believe the example below is pretty self explanatory. Keep in mind this is turned into a function at compile time, not during run time like Ruby, so it is a bit more limited.
Out of the box you have a strong standard library with tools for Base64, CSV, File, Gzip, HTTP, JSON, MarkDown, OAuth2, OpenSSL, URI, YAML, and Zip.
And many more! You can check the full list out at the API.
And when the standard library isn’t enough you’ve got shards! Which are the equivalent of Ruby’s gems.
Unlike bundler that is a separate library and not maintained by the language developers shards is built right in and completely supported. Everyone that has Crystal has shards.
shards.yml looks like this:
Sadly not everything is peachy in the land of Crystal, here’s a short list of things where Ruby has it beat:
While I don’t see Crystal disappearing I would be weary about building anything particularly large or important in it just yet.
If you’re still interested in trying Crystal out here is a list of gem/shard equivalents:
|ActiveRecord||Crecto, Granite, or Jennifer|
To find more just head over to CrystalShards and search. The list of shards grows longer every day.
I hope you’ve enjoyed my little introduction into Crystal!
If you are looking for a community, or even just some help, I’ve found r/crystal_programming to be a good resource.