Methods in Crystal

Crystal supports methods defined on struct types.

class Rect
  property width : Int32
  property height : Int32

  def initialize(@width : Int32, @height : Int32)
  end

  # This `area` method is defined on the `Rect` class.
  def area : Int32
    @width * @height
  end

  # Methods can be defined for either the class itself or instances.
  # Here's an example of an instance method.
  def perim : Int32
    2 * @width + 2 * @height
  end
end

def main
  r = Rect.new(width: 10, height: 5)

  # Here we call the 2 methods defined for our struct.
  puts "area: #{r.area}"
  puts "perim: #{r.perim}"

  # Crystal automatically handles method calls on references.
  # There's no need for explicit pointer dereferencing.
  rp = r
  puts "area: #{rp.area}"
  puts "perim: #{rp.perim}"
end

main

To run the program:

$ crystal methods.cr
area: 50
perim: 30
area: 50
perim: 30

In Crystal, classes are used instead of structs for defining custom types with methods. The property macro is used to create getter and setter methods for the struct fields.

Crystal doesn’t distinguish between value and reference types in method calls. All objects are passed by reference, and there’s no need for explicit pointer dereferencing.

The initialize method in Crystal is equivalent to a constructor in other languages. It’s called when creating a new instance of the class.

Crystal uses #{} for string interpolation inside double quotes, which is a more concise way to include variable values in strings compared to some other languages.

Next, we’ll look at Crystal’s mechanism for grouping and naming related sets of methods: modules and mixins.