Crystal for Rubyists

Although Crystal has a Ruby-like syntax, Crystal is a different language, not another Ruby implementation. For this reason, and mostly because it’s a compiled, statically typed language, the language has some big differences when compared to Ruby.

Crystal as a compiled language

Using the crystal command

If you have a program foo.cr:

  1. # Crystal
  2. puts "Hello world"

When you execute one of these commands, you will get the same output:

  1. $ crystal foo.cr
  2. Hello world
  3. $ ruby foo.cr
  4. Hello world

It looks like crystal interprets the file, but what actually happens is that the file foo.cr is first compiled to a temporary executable and then this executable is run. This behaviour is very useful in the development cycle as you normally compile a file and want to immediately execute it.

If you just want to compile it you can use the build command:

  1. $ crystal build foo.cr

This creates a foo executable, which you can then run with ./foo.

Note that this creates an executable that is not optimized. To optimize it, pass the --release flag:

  1. $ crystal build foo.cr --release

When writing benchmarks or testing performance, always remember to compile in release mode.

You can check other commands and flags by invoking crystal without arguments, or crystal with a command and no arguments (for example crystal build will list all flags that can be used with that command). Alternatively, you can read the manual.

Types

Bool

true and false are of type Bool rather than instances of classes TrueClass or FalseClass.

Integers

For Ruby’s Fixnum type, use one of Crystal’s integer types Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, or UInt64.

If any operation on a Ruby Fixnum exceeds its range, the value is automatically converted to a Bignum. Crystal will instead raise an OverflowError on overflow. For example:

  1. x = 127_i8 # An Int8 type
  2. x # => 127
  3. x += 1 # Unhandled exception: Arithmetic overflow (OverflowError)

Crystal’s standard library provides number types with arbitrary size and precision: BigDecimal, BigFloat, BigInt, BigRational.

See the language reference on Integers.

Regex

Global variables $` and $' are not supported (yet $~ and $1, $2, … are present). Use $~.pre_match and $~.post_match. Read more.

Pared-down instance methods

In Ruby where there are several methods for doing the same thing, in Crystal there may be only one. Specifically:

Ruby MethodCrystal Method
Enumerable#detectEnumerable#find
Enumerable#collectEnumerable#map
Object#respond_to?Object#responds_to?
length, size, countsize

Omitted Language Constructs

Where Ruby has a a couple of alternative constructs, Crystal has one.

  • trailing while/until are missing. Note however that if as a suffix is still available
  • and and or: use && and || instead with suitable parentheses to indicate precedence
  • Ruby has Kernel#proc, Kernel#lambda, Proc#new and ->, while Crystal uses Proc(*T, R).new and -> (see this for reference).
  • For require_relative "foo" use require "./foo"

No autosplat for arrays and enforced maximum block arity

  1. [[1, "A"], [2, "B"]].each do |a, b|
  2. pp a
  3. pp b
  4. end

will generate an error message like

  1. in line 1: too many block arguments (given 2, expected maximum 1)

However omitting unneeded arguments is fine (as it is in Ruby), ex:

  1. [[1, "A"], [2, "B"]].each do # no arguments
  2. pp 3
  3. end

Or

  1. def many
  2. yield 1, 2, 3
  3. end
  4. many do |x, y| # ignoring value passed in for "z" is OK
  5. puts x + y
  6. end

There is autosplat for tuples:

  1. [{1, "A"}, {2, "B"}].each do |a, b|
  2. pp a
  3. pp b
  4. end

will return the result you expect.

You can also explicitly unpack to get the same result as Ruby’s autosplat:

  1. [[1, "A"], [2, "B"]].each do |(a, b)|
  2. pp a
  3. pp b
  4. end

#each returns nil

In Ruby .each returns the receiver for many built-in collections like Array and Hash, which allows for chaining methods off of that, but that can lead to some performance and codegen issues in Crystal, so that feature is not supported. Alternately, one can use .tap.

Ruby:

  1. [1, 2].each { "foo" } # => [1, 2]

Crystal:

  1. [1, 2].each { "foo" } # => nil
  2. [1, 2].tap &.each { "foo" } # => [1, 2]

Reference

Reflection and Dynamic Evaluation

Kernel#eval() and the weird Kernel#autoload() are omitted. Object and class introspection methods Object#kind_of?(), Object#methods, Object#instance_methods, and Class#constants, are omitted as well.

In some cases macros can be used for reflection.

Semantic differences

Single versus double-quoted strings

In Ruby, string literals can be delimited with single or double quotes. A double-quoted string in Ruby is subject to variable interpolation inside the literal, while a single-quoted string is not.

In Crystal, string literals are delimited with double quotes only. Single quotes act as character literals just like say C-like languages. As with Ruby, there is variable interpolation inside string literals.

In sum:

  1. X = "ho"
  2. puts '"cute"' # Not valid in crystal, use "\"cute\"", %{"cute"}, or %("cute")
  3. puts "Interpolate #{X}" # works the same in Ruby and Crystal.

Triple quoted strings literals of Ruby or Python are not supported, but string literals can have newlines embedded in them:

  1. """Now,
  2. what?""" # Invalid Crystal use:
  3. "Now,
  4. what?" # Valid Crystal

Crystal supports many percent string literals, though.

The [] and []? methods

In Ruby the [] method generally returns nil if an element by that index/key is not found. For example:

  1. # Ruby
  2. a = [1, 2, 3]
  3. a[10] #=> nil
  4. h = {a: 1}
  5. h[1] #=> nil

In Crystal an exception is thrown in those cases:

  1. # Crystal
  2. a = [1, 2, 3]
  3. a[10] # => raises IndexError
  4. h = {"a" => 1}
  5. h[1] # => raises KeyError

The reason behind this change is that it would be very annoying to program in this way if every Array or Hash access could return nil as a potential value. This wouldn’t work:

  1. # Crystal
  2. a = [1, 2, 3]
  3. a[0] + a[1] # => Error: undefined method `+` for Nil

If you do want to get nil if the index/key is not found, you can use the []? method:

  1. # Crystal
  2. a = [1, 2, 3]
  3. value = a[4]? # => return a value of type Int32 | Nil
  4. if value
  5. puts "The number at index 4 is : #{value}"
  6. else
  7. puts "No number at index 4"
  8. end

The []? is just a regular method that you can (and should) define for a container-like class.

Another thing to know is that when you do this:

  1. # Crystal
  2. h = {1 => 2}
  3. h[3] ||= 4

the program is actually translated to this:

  1. # Crystal
  2. h = {1 => 2}
  3. h[3]? || (h[3] = 4)

That is, the []? method is used to check for the presence of an index/key.

Just as [] doesn’t return nil, some Array and Hash methods also don’t return nil and raise an exception if the element is not found: first, last, shift, pop, etc. For these a question-method is also provided to get the nil behaviour: first?, last?, shift?, pop?, etc.


The convention is for obj[key] to return a value or else raise if key is missing (the definition of “missing” depends on the type of obj) and for obj[key]? to return a value or else nil if key is missing.

For other methods, it depends. If there’s a method named foo and another foo? for the same type, it means that foo will raise on some condition while foo? will return nil in that same condition. If there’s just the foo? variant but no foo, it returns a truthy or falsey value (not necessarily true or false).

Examples for all of the above:

  • Array#[](index) raises on out of bounds, Array#[]?(index) returns nil in that case.
  • Hash#[](key) raises if the key is not in the hash, Hash#[]?(key) returns nil in that case.
  • Array#first raises if the array is empty (there’s no “first”, so “first” is missing), while Array#first? returns nil in that case. Same goes for pop/pop?, shift/shift?, last/last?
  • There’s String#includes?(obj), Enumerable#includes?(obj) and Enumerable#all?, all of which don’t have a non-question variant. The previous methods do indeed return true or false, but that is not a necessary condition.

for loops

for loops are not supported. Instead, we encourage you to use Enumerable#each. If you still want a for, you can add them via macro:

  1. macro for(expr)
  2. {{expr.args.first.args.first}}.each do |{{expr.name.id}}|
  3. {{expr.args.first.block.body}}
  4. end
  5. end
  6. for i [1, 2, 3] do # You can replace ∈ with any other word or character, just not `in`
  7. puts i
  8. end
  9. # note the trailing 'do' as block-opener!

Methods

In ruby, the following will raise an argument error:

  1. def process_data(a, b)
  2. # do stuff...
  3. end
  4. process_data(b: 2, a: "one")

This is because, in ruby, process_data(b: 2, a: "one") is syntax sugar for process_data({b: 2, a: "one"}).

In crystal, the compiler will treat process_data(b: 2, a: "one") as calling processData with the named arguments b: 2 and a: "one", which is the same as process_data("one", 2).

Properties

The ruby attr_accessor, attr_reader and attr_writer methods are replaced by macros with different names:

Ruby KeywordCrystal
attr_accessorproperty
attr_readergetter
attr_writersetter

Example:

  1. getter :name, :bday

In addition, Crystal added accessor macros for nilable or boolean instance variables. They have a question mark (?) in the name:

Crystal
property?
getter?

Example:

  1. class Person
  2. getter? happy = true
  3. property? sad = true
  4. end
  5. p = Person.new
  6. p.sad = false
  7. puts p.happy?
  8. puts p.sad?

Even though this is for booleans, you can specify any type:

  1. class Person
  2. getter? feeling : String = "happy"
  3. end
  4. puts Person.new.feeling?
  5. # => happy

Read more about getter?-macro) and/or property?-macro) in the documentation.

Consistent dot notation

For example File::exists? in Ruby becomes File.exists? in Crystal.

Crystal keywords

Crystal added some new keywords, these can still be used as method names, but need to be called explicitly with a dot: e.g. self.select{ |x| x > "good" }.

Available keywords

  1. abstract do if nil? select union
  2. alias else in of self unless
  3. as elsif include out sizeof until
  4. as? end instance_sizeof pointerof struct verbatim
  5. asm ensure is_a? private super when
  6. begin enum lib protected then while
  7. break extend macro require true with
  8. case false module rescue type yield
  9. class for next responds_to? typeof
  10. def fun nil return uninitialized

Private methods

Crystal requires each private method to be prefixed with the private keyword:

  1. private def method
  2. 42
  3. end

Pseudo Constants

Crystal provides a few pseudo-constants which provide reflective data about the source code being executed.

Read more about Pseudo Constants in the Crystal documentation.

CrystalRubyDescription
FILEFILEThe full path to the currently executing crystal file.
DIRdirThe full path to the directory where the currently executing crystal file is located.
LINELINEThe current line number in the currently executing crystal file.
END_LINE-The line number of the end of the calling block. Can only be used as a default value to a method parameter.

Tip

Further reading about __DIR__ vs. __dir__:

Crystal Shards for Ruby Gems

Many popular Ruby gems have been ported or rewritten in Crystal. Here are some of the equivalent Crystal Shards for Ruby Gems.


For other questions regarding differences between Ruby and Crystal, visit the FAQ.