튜플
튜플 (Tuple)
Tuple은 보통 튜플 리터럴로 만듭니다:
tuple = {1, "hello", 'x'} # Tuple(Int32, String, Char)
tuple[0] # => 1 (Int32)
tuple[1] # => "hello" (String)
tuple[2] # => 'x' (Char)
빈 튜플을 만들려면 Tuple.new를 써요.
튜플 타입을 표기할 때는 이렇게 적습니다:
# The type denoting a tuple of Int32, String and Char
Tuple(Int32, String, Char)
타입 제한(Type restriction), 제네릭 타입 인자 등 타입이 필요한 자리에서는 타입 문법에 나온 더 짧은 문법을 쓸 수 있어요:
# An array of tuples of Int32, String and Char
Array({Int32, String, Char})
스플랫 펼치기 (Splat Expansion)
튜플 리터럴 안에서 스플랫 연산자를 쓰면 여러 값을 한 번에 펼칠 수 있습니다. 스플랫되는 값은 반드시 다른 튜플이어야 해요.
tuple = {1, *{"hello", 'x'}, 2} # => {1, "hello", 'x', 2}
typeof(tuple) # => Tuple(Int32, String, Char, Int32)
tuple = {3.5, true}
tuple = {*tuple, *tuple} # => {3.5, true, 3.5, true}
typeof(tuple) # => Tuple(Float64, Bool, Float64, Bool)
출처: Crystal 공식 문서
더 알아보기 (Learn more)
- 스플랫과 튜플 (Splats and tuples) — 가변 인자 처리
- NamedTuple 리터럴 — 이름 붙은 튜플