Work on the language began in June 2011,[9] with the aim of merging the elegance and productivity of Ruby with the speed, efficiency, and type safety of a compiled language.[10][9] Initially named Joy, it was quickly renamed to Crystal.[9]
The Crystal compiler was first written in Ruby, but later rewritten in Crystal, thus becoming self-hosting, as of November 2013[update].[11] The first official version was released in June 2014.[12] In July 2016, Crystal joined the TIOBE index.
Description
Although resembling the Ruby language in syntax, Crystal compiles to much more efficient native code using an LLVM backend, at the cost of precluding the dynamic aspects of Ruby. The advanced global type inference used by the Crystal compiler, combined with union types, gives it more the feel of a higher-level scripting language than many other comparable programming languages. It has automated garbage collection and offers a Boehm collector. Crystal possesses a macro system and supports generics as well as method and operator overloading. Its concurrency model is inspired by communicating sequential processes (CSP) and implements lightweight fibers and channels (for interfiber communication), inspired by Go.[4]
Examples
Hello World
This is the simplest way to write the Hello World program in Crystal:
require"http/server"server=HTTP::Server.newdo|context|context.response.content_type="text/plain"context.response.print"Hello world! The time is #{Time.local}"endserver.bind_tcp("0.0.0.0",8080)puts"Listening on http://0.0.0.0:8080"server.listen
The following code defines an array containing different types with no usable common ancestor. Crystal automatically creates a union type out of the types of the individual items.
desired_things=[:unicorns,"butterflies",1_000_000]ptypeof(desired_things.first)# typeof returns the compile time type, here (Symbol | String | Int32)pdesired_things.first.class# the class method returns the runtime type, here Symbol
Concurrency
Channels can be used to communicate between fibers, which are initiated using the keyword spawn.
channel=Channel(Int32).newspawndoputs"Before first send"channel.send(1)puts"Before second send"channel.send(2)endputs"Before first receive"value=channel.receiveputsvalue# => 1puts"Before second receive"value=channel.receiveputsvalue# => 2