Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Control Flow and Methods

Methods and Arguments

Define Crystal methods with default values, named arguments, splats, double splats, return types, the implicit return and the short one-line form, with Ruby stand-ins you can run.

Methods are how you name and reuse a piece of behaviour. Crystal methods look like Ruby's and are just as flexible: default values, keyword-style named arguments, variable argument lists and block parameters. Because the compiler specialises each call, all this flexibility costs nothing at run time. This lesson covers the shapes of method definitions and calls.

Crystal listings are read-only here. The runnable Ruby stand-ins use the same method syntax; differences are noted.

Defining and calling

CRYSTAL
def greet(name)
  "Hello, #{name}!"
end

puts greet("Ada")

A method returns the value of its last expression. You rarely write return, except to leave early.

CRYSTAL
def sign(n : Int32) : String
  return "zero" if n == 0
  n > 0 ? "positive" : "negative"
end

Parentheses are optional on calls (puts greet "Ada" works) but keep them on anything that is not a one-word call; they remove ambiguity.

Unlike recent Ruby, Crystal has no one-line def name = expression form, so even a short method uses def ... end.

Default values

CRYSTAL
def power(base, exponent = 2)
  base ** exponent
end

puts power(5)      # 25
puts power(2, 10)  # 1024

Default values can be any expression and can use earlier parameters:

CRYSTAL
def box(width, height = width)
  width * height
end

puts box(4)        # 16
puts box(4, 3)     # 12

Named arguments

Every parameter can be passed by name, in any order. This makes calls self-describing:

CRYSTAL
def connect(host, port = 80, secure = false)
  "#{secure ? "https" : "http"}://#{host}:#{port}"
end

puts connect("example.com", secure: true)
puts connect(host: "example.com", port: 8080)
puts connect(port: 3000, host: "localhost")

Positional arguments come first, named ones after. If a method has a parameter with an external name, the caller must use the external name, and the method body uses the internal one:

CRYSTAL
def move(distance, to destination : String)
  "#{distance} units to #{destination}"
end

puts move(5, to: "the door")

The word before the parameter (to) is the label used at the call site; destination is the variable inside. It reads like a sentence.

To force callers to name some arguments, put a bare * in the list. Everything after it is named-only:

CRYSTAL
def create(name, *, admin = false, active = true)
  "#{name} admin=#{admin} active=#{active}"
end

puts create("ada", admin: true)
Ruby Stand-in: defaults and keyword arguments in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In Ruby you must declare keyword parameters with a colon (host:). In Crystal every ordinary parameter can already be named at the call site, so the definition stays simple.

Variable argument lists: splat

A parameter starting with * collects extra positional arguments into a tuple:

CRYSTAL
def sum(*numbers)
  total = 0
  numbers.each { |n| total += n }
  total
end

puts sum(1, 2, 3)      # 6
puts sum()             # 0
puts sum(10, 20)       # 30

Use the splat at the call site to expand an array:

CRYSTAL
values = [4, 5, 6]
puts sum(*values)      # 15

A double splat **options collects named arguments into a NamedTuple:

CRYSTAL
def style(**props)
  props.map { |key, value| "#{key}: #{value}" }.join("; ")
end

puts style(color: "red", size: 12)   # color: red; size: 12

Returning several values

Return a tuple and unpack it:

CRYSTAL
def min_max(numbers : Array(Int32))
  {numbers.min, numbers.max}
end

low, high = min_max([3, 9, 1, 7])
puts "#{low}..#{high}"     # 1..9

A tuple is a fixed-size, typed, stack-allocated group: {Int32, Int32} is a different type from {Int32, String}. It is cheaper than an array and lets each element have its own type.

Blocks and yield (preview)

A method can take a block and run it with yield:

CRYSTAL
def twice
  yield
  yield
end

twice { puts "hello" }     # prints hello two times

Blocks have their own lesson in the collections chapter. For now remember that a method that contains yield is called with a do ... end or { } block after the arguments.

Ruby Stand-in: splat, double splat and tuples in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Visibility

By default methods are public. Make one private to hide it from the outside:

CRYSTAL
class Counter
  def total
    compute
  end

  private def compute
    42
  end
end

Private methods can be called without an explicit receiver (compute), but not as counter.compute from outside. protected allows calls from other instances of the same class. Top-level methods are visible everywhere in the program.

Recursion

A method can call itself. Crystal does not optimise tail calls, so very deep recursion can overflow the stack; use a loop for deep structures.

CRYSTAL
def factorial(n : Int32) : Int64
  n <= 1 ? 1_i64 : n * factorial(n - 1)
end

puts factorial(10)    # 3628800

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a Crystal method return when there is no explicit return?

    The last evaluated expression is the return value.
  2. 2. How do you make admin a named-only argument?

    Parameters after a bare * can only be passed by name.
  3. 3. What type does *numbers collect extra arguments into?

    A splat parameter becomes a Tuple, which keeps each element's type.
  4. 4. What does def move(distance, to destination) allow?

    The external name to is used at the call site; destination is the name inside the method.

Summary

  • Methods return their last expression; add : Type to declare the return type.
  • Defaults can use earlier parameters; every parameter can be passed by name.
  • A bare * makes later parameters named-only; *args and **opts collect extras.
  • Return a tuple for several values and unpack with multiple assignment.
  • private and protected control who may call a method.

Next: Overloading, Return Types and Procs