Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Crystal

Learn Crystal - 10 Code Examples & CST Typing Practice Test

Crystal is a modern, statically typed, compiled programming language with syntax heavily inspired by Ruby. It aims to combine the efficiency and speed of compiled languages with the readability and productivity of Ruby, supporting type inference, concurrency, and high-performance applications.

View all 10 Crystal code examples →
Crystal Counter and Theme ToggleCrystal Simple AdditionCrystal FactorialCrystal Fibonacci SequenceCrystal Max of Two NumbersCrystal List SumCrystal Even Numbers FilterCrystal Conditional Counter IncrementCrystal Resettable CounterCrystal Theme Toggle Only

Learn CRYSTAL with Real Code Examples

Updated Nov 20, 2025

Explain

Crystal compiles directly to native code for high performance.

It features static type checking with powerful type inference, reducing boilerplate.

Used for web development, CLI tools, system utilities, and high-performance applications.

Core Features

Classes, modules, structs, and enums

Generics and type inference

Error handling with exceptions

Compile-time macros

Standard library for networking, HTTP, JSON, and more

Basic Concepts Overview

Crystal syntax and expressions

Variables, types, and constants

Classes, structs, and modules

Methods, blocks, and lambdas

Error handling with `raise` and `rescue`

Project Structure

src/ (source code)

lib/ (dependencies via Shards)

spec/ (unit tests)

shard.yml (dependency config)

bin/ (compiled binaries)

Building Workflow

Write `.cr` source files

Manage dependencies with Shards

Compile using `crystal build file.cr`

Run compiled binary

Debug with compiler warnings and logging

Difficulty Use Cases

Beginner: CLI utilities and small scripts

Intermediate: web apps with Kemal or Amber

Advanced: concurrent microservices

Expert: system-level high-performance tools

Comparisons

Syntax similar to Ruby, but compiled and statically typed

Faster than interpreted languages like Ruby or Python

Less mature ecosystem than mainstream languages

Macro system allows metaprogramming unlike Go

Concurrency model simpler than full OS threads

Versioning Timeline

2011 - Crystal first introduced

2014 - Shards dependency manager released

2016 - Kemal web framework launched

2018 - Amber web framework stabilization

2020-2025 - Compiler improvements and ecosystem growth

Glossary

Shards: Crystal’s package manager

Fiber: lightweight concurrency primitive

Macro: compile-time code generator

Spec: built-in testing module

Type inference: compiler deduces variable types

Installation Setup

Install Crystal compiler via package manager or from source

Verify installation with `crystal --version`

Install Shards (dependency manager)

Create project with `crystal init app project_name`

Build and run sample project

Environment Setup

Install Crystal compiler

Install Shards

Set PATH for Crystal binaries

Verify with `crystal --version`

Run sample application

Config Files

shard.yml for dependencies

.cr files for source code

config/ for environment settings

spec/ for tests

bin/ for compiled binaries

Cli Commands

crystal build file.cr

crystal run file.cr

crystal spec

shards install

crystal tool format

Internationalization

UTF-8 strings supported

Locale-specific formatting via libraries

Web frameworks support i18n

No built-in multi-language runtime

Strings and symbols fully Unicode-compatible

Accessibility

Crystal compiler with clear error messages

REPL via `crystal play`

Rich documentation and tutorials

Active GitHub community

Language server for IDEs

Ui Styling

Primarily CLI or web backend

Web rendering via Kemal/Amber

No native GUI focus

Integration with frontend via JSON/HTTP

Console output formatting supported

State Management

Variables and constants in scope

Fiber-local state for concurrency

Immutable types for safety

Shared memory via channels

Global state discouraged

Data Management

Arrays, hashes, tuples

Structs and classes

IO streams and JSON handling

Database queries via ORM

Shards for external libraries

Architecture

LLVM-based compiler generates native binaries

Static type checking at compile-time

Standard library written in Crystal

Supports fibers for cooperative concurrency

Compile-time macros expand code before runtime

Rendering Model

Source code compiled to native binary

Static type checking at compile-time

Macros expanded before compilation

Execution via compiled machine code

Fibers provide lightweight concurrency

Architectural Patterns

MVC for web frameworks

Fiber-based concurrency pipelines

CLI tool modular design

Macro-driven code generation

Microservice-oriented structure

Real World Architectures

Web backends

CLI utilities

Microservices

Data processing pipelines

High-performance APIs

Design Principles

Readable, Ruby-inspired syntax

Static typing with inference

Compiled to native binaries for speed

Concurrency via fibers

Macro-based compile-time metaprogramming

Scalability Guide

Use fibers for concurrent tasks

Split code into modules

Compile to optimized binaries

Use Shards for dependency management

Profile and optimize hot paths

Migration Guide

Migrate Ruby scripts to Crystal for performance

Replace dynamic typing with static types

Port web apps to Kemal/Amber

Refactor blocking IO to fibers

Adjust gems to Shards libraries

Performance Notes

Compiled native binaries run fast

Use fibers for lightweight concurrency

Avoid excessive object allocations in hot loops

Use structs for value types to reduce GC overhead

Leverage compile-time macros for repeated patterns

Security Notes

Validate user inputs for web applications

Use HTTPS for network requests

Handle exceptions to prevent leaks

Sanitize data for database insertion

Follow secure coding practices for concurrency

Monitoring Analytics

Logging for runtime

Fiber execution tracing

Compile-time warnings and errors

Benchmark hot paths

Monitor web requests in Kemal/Amber apps

Code Quality

Use type inference wisely

Follow Ruby-inspired readable syntax

Write unit tests with Spec

Modularize code for maintainability

Document fiber usage and concurrency

Practical Examples

CLI tool parsing arguments

REST API backend

Concurrent web crawler

JSON data processor

Simple microservice with fiber-based concurrency

Troubleshooting

Check type mismatches reported by compiler

Verify Shards dependencies

Use `--error-trace` for detailed compilation errors

Ensure correct Crystal version

Debug runtime exceptions with logging

Testing Guide

Use built-in `Spec` module

Write unit tests in `spec/` directory

Run `crystal spec`

Test concurrency edge cases

Use mocks and fixtures for IO testing

Deployment Options

Deploy compiled binaries directly

Containerized deployment (Docker)

Serverless functions with native binary

Package CLI tools for distribution

Cloud deployment for web backends

Tools Ecosystem

Crystal compiler

Shards dependency manager

Kemal web framework

Amber web framework

crystal tool for testing & formatting

Integrations

HTTP servers and REST APIs

Database libraries (PostgreSQL, SQLite, MySQL)

JSON/XML processing

CLI tools integration

Interfacing with C libraries via `lib`

Productivity Tips

Leverage Shards for library management

Use macros for repeated code patterns

Write tests in parallel with development

Use fiber concurrency for efficient IO

Keep code clean and Ruby-like for readability

Challenges

Build CLI argument parser

Create small REST API

Implement concurrent task runner

Write JSON processor

Develop microservice with fibers

Learning Path

Learn Ruby syntax basics

Understand Crystal type system and syntax

Write CLI tools and small scripts

Learn web frameworks (Kemal/Amber)

Master concurrency and fibers

Skill Improvement Plan

Week 1: Syntax, types, and variables

Week 2: Classes, modules, methods, and exceptions

Week 3: Web frameworks and HTTP handling

Week 4: Fibers, macros, and high-performance patterns

Interview Questions

Explain Crystal’s type inference system.

Difference between structs and classes?

How do fibers work in Crystal?

What is Shards used for?

How do macros work at compile-time?

Cheat Sheet

crystal build file.cr # compile

crystal run file.cr # compile & run

crystal spec # run tests

shards install # install dependencies

fiber = Fiber.new { ... }

Books

Programming Crystal

Crystal in Action

Crystal for Rubyists

Tutorials

Crystal Lang Getting Started

Kemal Web Framework Tutorial

Crystal Concurrency & Fibers Guide

Official Docs

Crystal Lang Official Documentation

Shards Dependency Manager Guide

Kemal Web Framework Documentation

Community Links

Crystal Forum

Crystal GitHub

Crystal Slack Community

Community Support

Crystal-lang official forums

Crystal Slack community

GitHub Crystal repositories

StackOverflow Crystal tag

Crystal blog tutorials

Monetization

Freelance backend development

High-performance CLI tools

Microservices consulting

Web application startups

Open-source library development

Future Roadmap

Improved compiler speed

Expanded ecosystem and libraries

Better concurrency and async primitives

Enhanced web frameworks

Continued Ruby-inspired syntax evolution

When Not To Use

GUI-heavy desktop applications

Mobile app development

Machine learning with limited libraries

Enterprise applications requiring large ecosystems

Projects needing mature third-party libraries

Final Summary

Crystal combines Ruby-like syntax with compiled performance and static typing.

Ideal for web backends, CLI tools, and concurrent applications.

Smaller but growing ecosystem with modern features.

Focuses on productivity without sacrificing execution speed.

Faq

Is Crystal ready for production?

Yes - used in web backends, CLI tools, and microservices.

Is Crystal similar to Ruby?

Yes - syntax is Ruby-like, but it is compiled and statically typed.

Does Crystal have concurrency?

Yes - via fibers and channels.

Can I use C libraries?

Yes - Crystal has native C interop.

Code Sample Descriptions

1

Crystal Counter and Theme Toggle

count = 0
is_dark = false

def update_ui(count, is_dark)
    puts "Counter: #{count}"
    puts "Theme: #{is_dark ? "Dark" : "Light"}"
end

def increment(count, is_dark)
    count += 1
    update_ui(count, is_dark)
    count
end

def decrement(count, is_dark)
    count -= 1
    update_ui(count, is_dark)
    count
end

def reset(count, is_dark)
    count = 0
    update_ui(count, is_dark)
    count
end

def toggle_theme(is_dark)
    is_dark = !is_dark
    update_ui(count, is_dark)
    is_dark
end

# Simulate actions
update_ui(count, is_dark)
count = increment(count, is_dark)
count = increment(count, is_dark)
is_dark = toggle_theme(is_dark)
count = decrement(count, is_dark)
count = reset(count, is_dark)

Demonstrates a simple counter with theme toggling using Crystal variables and console output.

Let’s Try →
2

Crystal Simple Addition

def add(a, b)
    a + b
end

puts add(10, 20)

Adds two numbers and prints the result.

Let’s Try →
3

Crystal Factorial

def factorial(n)
    return 1 if n <= 1
    n * factorial(n - 1)
end

puts factorial(5)

Calculates factorial recursively.

Let’s Try →
4

Crystal Fibonacci Sequence

def fib(n)
    return n if n < 2
    fib(n - 1) + fib(n - 2)
end

10.times do |i|
    puts fib(i)
end

Generates first 10 Fibonacci numbers.

Let’s Try →
5

Crystal Max of Two Numbers

def max(a, b)
    a > b ? a : b
end

puts max(10, 20)

Finds the maximum of two numbers.

Let’s Try →
6

Crystal List Sum

arr = [1,2,3,4,5]
puts arr.sum

Sums elements of an array.

Let’s Try →
7

Crystal Even Numbers Filter

arr = [1,2,3,4,5]
arr.each do |x|
    puts x if x.even?
end

Prints even numbers from an array.

Let’s Try →
8

Crystal Conditional Counter Increment

count = 3
count += 1 if count < 5
puts count

Increment counter only if less than 5.

Let’s Try →
9

Crystal Resettable Counter

count = 0
count += 1
count += 1
puts count
count = 0
puts count

Counter that increments and can be reset.

Let’s Try →
10

Crystal Theme Toggle Only

is_dark = false
puts is_dark ? "Dark" : "Light"
is_dark = !is_dark
puts is_dark ? "Dark" : "Light"
is_dark = !is_dark
puts is_dark ? "Dark" : "Light"

Toggles theme multiple times.

Let’s Try →

Frequently Asked Questions about Crystal

What is Crystal?

Crystal is a modern, statically typed, compiled programming language with syntax heavily inspired by Ruby. It aims to combine the efficiency and speed of compiled languages with the readability and productivity of Ruby, supporting type inference, concurrency, and high-performance applications.

What are the primary use cases for Crystal?

Web applications (via Kemal, Amber frameworks). Command-line tools. Microservices and APIs. High-performance backend services. System utilities and scripting. Prototyping with production-ready performance

What are the strengths of Crystal?

High performance due to compilation to native code. Readable Ruby-like syntax. Strong static typing with minimal verbosity. Macros for metaprogramming and code reuse. Good concurrency model with lightweight fibers

What are the limitations of Crystal?

Smaller ecosystem than Ruby or Python. Slower compiler for large projects. Limited libraries for certain domains. Less community support compared to mainstream languages. Still maturing in tooling and IDE support

How can I practice Crystal typing speed?

CodeSpeedTest offers 10+ real Crystal code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.