Learn CRYSTAL with Real Code Examples
Updated Nov 20, 2025
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.
2
Crystal Simple Addition
def add(a, b)
a + b
end
puts add(10, 20)
Adds two numbers and prints the result.
3
Crystal Factorial
def factorial(n)
return 1 if n <= 1
n * factorial(n - 1)
end
puts factorial(5)
Calculates factorial recursively.
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.
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.
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.
8
Crystal Conditional Counter Increment
count = 3
count += 1 if count < 5
puts count
Increment counter only if less than 5.
9
Crystal Resettable Counter
count = 0
count += 1
count += 1
puts count
count = 0
puts count
Counter that increments and can be reset.
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.