Organizing your code in files
Writing code in a single file is fine for some quick tests or very small applications, but anything else will eventually need to be organized in multiple files. There is always the main file, which is the one you pass to the crystal run
or the crystal build
command, but this file can reference code in other files with the require
keyword. Compilation will always begin by analyzing this main file and then analyzing any file it references, and so on, recursively.
Let's analyze an example:
- First, create a file named
factorial.cr
:def factorial(n) (1..n).product end
- Then, create a file named
program.cr
:require "./factorial" (1..10).each do |i| puts "#{i}! = #{factorial(i)}" end
In this example, require "./factorial"
will search for a file named factorial.cr
in the same folder as program.cr
and import everything it defines. There is no way to select only part of what the required...