01
Einstieg
Hello World
Crystal-Syntax ist Ruby sehr ähnlich.
crystal
puts "Hello, World!"Variablen
Variablen sind in Crystal standardmäßig unveränderlich.
crystal
x = 10 # immutable
y = 20
puts x + yFunktionen
Kein explizites return nötig; der letzte Ausdruck wird zurückgegeben.
crystal
def add(a, b)
a + b
end
puts add(3, 4)Ausführen & Bauen
crystal build erzeugt eine native Binärdatei.
crystal
# crystal run main.cr
# crystal build main.cr --release02
Typen & Datenstrukturen
Grundlegende Typen
Crystal leitet Typen zur Kompilierzeit ab.
crystal
i = 1 # Int32
f = 3.14 # Float64
s = "hello" # String
b = true # Bool
a = [1, 2, 3] # Array(Int32)Hash
Hash ist das Äquivalent zu Rubys Hash.
crystal
h = {"a" => 1, "b" => 2}
puts h["a"]
h["c"] = 3Tuple
Tupel sind Arrays fester Größe mit gemischten Typen.
crystal
t = {1, "hello", true}
puts t[0]
puts t[1]Named Tuple
Named Tuples verwenden Symbole als Schlüssel.
crystal
nt = {x: 1, y: 2}
puts nt[:x]
puts nt[:y]03
Kontrollfluss
If-Else
If-elsif-else im Ruby-Stil.
crystal
n = 5
if n > 3
puts "big"
elsif n == 3
puts "three"
else
puts "small"
endCase
case/when für Pattern Matching.
crystal
day = "Mon"
case day
when "Mon" then puts "Monday"
when "Tue" then puts "Tuesday"
else puts "Other"
endBlocks
Blocks sind Closures, die an Methoden übergeben werden.
crystal
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].map { |n| n * 2 }Was this helpful?