Work on the language began in June 2011, with the purpose of creating a language with the elegance and productivity of Ruby and the speed, efficiency, and type safety of a compiled language. Initially named Joy, it was quickly renamed to Crystal. The Crystal compiler was first written in Ruby, but later rewritten in Crystal, thus becoming self-hosting, as of November 2013. The first official version was released in June 2014. 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. However, the advanced global type inference used by the Crystal compiler, combined with the use of union types, gives Crystal the feel of a higher-level scripting language more so than many other comparable programming languages. The language has automated garbage collection and currently offers a Boehm collector. Crystal possesses a macro system and supports generics, and method and operator overloading. Crystal's concurrency model is inspired by communicating sequential processes and implements light-weight fibers and channels inspired by the language Go.
The same as in Ruby. Or using an object-oriented programming style: class Greeter def initialize end def salute puts "Hello #!" end end g = Greeter.new g.salute
HTTP server
require "http/server" server = HTTP::Server.new do |context| context.response.content_type = "text/plain" context.response.print "Hello world! The time is #" end server.bind_tcp puts "Listening on http://0.0.0.0:8080" server.listen
require "socket" def handle_client message = client.gets client.puts message end server = TCPServer.new while client = server.accept? spawn handle_client end
Type inference and union types
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 = p typeof # typeof returns the compile time type, here p desired_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.new spawn do puts "Before first send" channel.send puts "Before second send" channel.send end puts "Before first receive" value = channel.receive puts value # => 1 puts "Before second receive" value = channel.receive puts value # => 2