Skip to content

Crystal Hoja de referencia

Sintaxis estilo Ruby con rendimiento estilo C: tipado estático y compilado.

01

Primeros pasos

Hello World

La sintaxis de Crystal es muy parecida a la de Ruby.

crystal
puts "Hello, World!"

Variables

Las variables son inmutables por defecto en Crystal.

crystal
x = 10          # immutable
y = 20
puts x + y

Funciones

No hace falta return explícito; la última expresión se devuelve.

crystal
def add(a, b)
  a + b
end

puts add(3, 4)

Ejecutar y compilar

crystal build produce un binario nativo.

crystal
# crystal run main.cr
# crystal build main.cr --release
02

Tipos y estructuras de datos

Tipos básicos

Crystal infiere los tipos en tiempo de compilación.

crystal
i = 1           # Int32
f = 3.14        # Float64
s = "hello"     # String
b = true        # Bool
a = [1, 2, 3]   # Array(Int32)

Hash

Hash es el equivalente del Hash de Ruby.

crystal
h = {"a" => 1, "b" => 2}
puts h["a"]
h["c"] = 3

Tuple

Las tuplas son arrays de tamaño fijo con tipos mixtos.

crystal
t = {1, "hello", true}
puts t[0]
puts t[1]

Named Tuple

Las named tuples usan symbols como claves.

crystal
nt = {x: 1, y: 2}
puts nt[:x]
puts nt[:y]
03

Flujo de control

If-Else

if-elsif-else al estilo Ruby.

crystal
n = 5
if n > 3
  puts "big"
elsif n == 3
  puts "three"
else
  puts "small"
end

Case

case/when para pattern matching.

crystal
day = "Mon"
case day
when "Mon" then puts "Monday"
when "Tue" then puts "Tuesday"
else puts "Other"
end

Blocks

Los blocks son closures que se pasan a las funciones.

crystal
[1, 2, 3].each do |n|
  puts n
end

[1, 2, 3].map { |n| n * 2 }

Was this helpful?