Learn/Crystal/6. Functions
Lesson 6 of 8
Sign in

Crystal, lesson 6

Functions

As a program grows, you want to give a piece of logic a name, reuse it, and test it on its own. In Crystal these are called methods, and you define them with def.

Defining a method

A method returns the value of its last expression, so there is usually no need for return. You call it with parentheses around the arguments. (You may drop them, as with puts, but for your own methods they make the code easier to read.)

Types: optional, but helpful

Notice that total has no types. The compiler works them out from each call: total(4, 3) makes a version for integers, and total(2.5, 2) would make another for floats. You can still add type restrictions to parameters and a return type after the parentheses:

Now total("4", 3) is a compile error with a clear message. Restrictions document what a method expects and catch mistakes early, so they are a good habit for anything bigger than a few lines.

2 exercises to try what you just read.

Exercise 1

Prime checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Volume knob

Press Ctrl Enter or Check to test your code.

Early returns and predicates

return leaves a method immediately, which is handy for special cases:

A method name may end in ?. By convention that means it answers a yes/no question and returns a Bool, like even?(n) or prime?(n).

Default and named arguments

A parameter can have a default value, and callers may pass arguments by name for clarity:

Scope: what a method can see

A method only sees its own parameters and the variables it creates inside its body. Local variables from the top of your file are invisible inside def. This surprises many people:

Either pass rate in as a parameter or make it a constant (RATE = 20), because constants are visible everywhere. This rule keeps methods self-contained: you can understand one by reading it alone.

Further reading

  • Crystal reference: Methods and instance variables
  • Crystal reference: def
  • Crystal reference: Type restrictions
  • Crystal reference: Default and named arguments

Write prime?(n : Int32) : Bool, which returns true when a number is prime (it has exactly two divisors, 1 and itself) and false otherwise. Numbers below 2 are not prime.

Try divisors d = 2, 3, 4, ... while d * d <= n, and return false as soon as one divides n evenly.

Input: one whole number. Output: N is prime or N is not prime.

prints 97 is prime.

A speaker's volume must stay between a lowest and a highest setting. Write limit(value, low, high), which returns:

  • low if the value is below low,
  • high if the value is above high,
  • the value itself otherwise.

Input: three lines: the requested value, then low, then high (low is never above high). Output: the limited value.

def total(price, quantity)
  price * quantity
end

puts total(4, 3)   # 12
def total(price : Int32, quantity : Int32) : Int32
  price * quantity
end
def describe(age : Int32) : String
  return "not born yet" if age < 0
  return "minor" if age < 18
  "adult"
end
def greet(name, greeting = "Hello")
  "#{greeting}, #{name}!"
end

puts greet("Ada")                     # Hello, Ada!
puts greet("Ada", greeting: "Howdy")  # Howdy, Ada!
rate = 20
def with_vat(net)
  net + net * rate // 100   # compile error: rate is not defined here
end
97