Class methods

Class methods are methods associated to a class or module instead of a specific instance.

  1. module CaesarCipher
  2. def self.encrypt(string : String)
  3. string.chars.map { |char| ((char.upcase.ord - 52) % 26 + 65).chr }.join
  4. end
  5. end
  6. CaesarCipher.encrypt("HELLO") # => "URYYB"

Class methods are defined by prefixing the method name with the type name and a period.

  1. def CaesarCipher.decrypt(string : String)
  2. encrypt(string)
  3. end

When they’re defined inside a class or module scope it is easier to use self instead of the class name.

Class methods can also be defined by extending a Module.

A class method can be called under the same name as it was defined (CaesarCipher.decrypt("HELLO")). When called from within the same class or module scope the receiver can be self or implicit (like encrypt(string)).

A class method is not in scope within an instance of the class; instead, access it through the class scope.

  1. class Foo
  2. def self.shout(str : String)
  3. puts str.upcase
  4. end
  5. def baz
  6. self.class.shout("baz")
  7. end
  8. end
  9. Foo.new.baz # => BAZ

Constructors

Constructors are normal class methods which create a new instance of the class. By default all classes in Crystal have at least one constructor called new, but they may also define other constructors with different names.