Skip to content

Crystal 치트시트

Ruby와 비슷한 문법에 C급 성능을 내는 정적 타입 컴파일 언어입니다.

01

시작하기

Hello World

Crystal의 문법은 Ruby와 매우 유사합니다.

crystal
puts "Hello, World!"

변수

Crystal에서 변수는 기본적으로 불변(immutable)입니다.

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

함수

return을 명시할 필요가 없으며, 마지막 표현식이 반환됩니다.

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

puts add(3, 4)

실행과 빌드

crystal build는 네이티브 바이너리를 생성합니다.

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

타입과 자료구조

기본 타입

Crystal은 컴파일 시점에 타입을 추론합니다.

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

Hash

Hash는 Ruby의 Hash에 해당하는 자료구조입니다.

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

Tuple

Tuple은 크기가 고정되고 여러 타입을 섞을 수 있는 배열입니다.

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

Named Tuple

Named tuple은 심볼을 키로 사용합니다.

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

제어 흐름

If-Else

Ruby 스타일의 if-elsif-else입니다.

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

Case

case/when으로 패턴 매칭을 합니다.

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

블록

블록은 메서드에 전달되는 클로저입니다.

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

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

Was this helpful?