Basics

Crystal Running Code

Running Crystal Code

Crystal code runs via crystal run or crystal build with .cr files.

Introduction to Running Crystal Code

Crystal is a programming language that is both powerful and easy to use, offering syntax familiar to Ruby developers. In this guide, we'll explore how to execute Crystal code using two primary methods: crystal run and crystal build. Each method offers distinct advantages depending on your development needs.

Using 'crystal run' to Execute Code

The crystal run command is the simplest way to execute Crystal code. It compiles and runs the code in a single step, making it ideal for development and testing. This command is particularly useful when you want to quickly test snippets of code without the need for generating an executable file.

Compiling with 'crystal build'

If you need to generate an executable file for distribution or deployment, crystal build is the command to use. This compiles the code into a binary, which can be executed independently of the Crystal compiler.

Understanding File Extensions and Naming

Crystal source files use the .cr extension. When using crystal build, the resulting executable will have no extension on UNIX-based systems and a .exe extension on Windows. It's a good practice to name your source files meaningfully to reflect their purpose.

Handling Command-Line Arguments

Both crystal run and crystal build support command-line arguments, which can be accessed within your Crystal programs. This is useful for creating scripts and applications that require user input at runtime.

Conclusion

Whether you're testing small snippets of code or compiling full applications, Crystal's crystal run and crystal build commands provide the flexibility you need to effectively manage your development process. Understanding these commands will help you make the most of Crystal's capabilities as you continue to learn and explore the language.