Skip to content

Crystal チートシート

Ruby 風の構文と C 風のパフォーマンスを持つ静的型付けコンパイル言語。

01

はじめに

Hello World

Crystal の構文は Ruby によく似ています。

crystal
puts "Hello, World!"

変数

Crystal では変数がデフォルトで不変(イミュータブル)です。

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 は Ruby の Hash に相当します。

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

タプル

タプルは固定長で混在した型を扱える配列です。

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

名前付きタプル

名前付きタプルはキーにシンボルを使います。

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?