Crystal Notes: Tuples
Published: 2nd of August 2021
Tuples
A Tuple in Crystal is a group if related values of possibly different types.
crystal
# Define a Tuple.
stuff_and_things = {"stuff", :things, 42}
# Access a Tuple element.
stuff_and_things[0] # => stuff
# Deduce the type of stuff_and_things
typeof(stuff_and_things) # => Tuple(String, Symbol, Int32)
Named Tuples
NamedTuples allow you to create a key/value pair version of a Tuple.
crystal
# Define a NamedTuple.
stuff_and_things = {stuff: "stuff", things: :things, the_answer: 42}
# Access a NamedTuple element.
stuff_and_things[:the_answer] # => 42
# Deduce the type of stuff_and_things
typeof(stuff_and_things) # => NamedTuple(stuff: String, things: Symbol, the_answer: Int32)
Consideration
- Tuples have a fixed size and are stack-allocated.
- Preference should be given to tuples over arrays for fixed size collections.
- NamedTuple keys are of the Symbol type.
Links
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/syntax_and_semantics/literals/tuple.html
https://crystal-lang.org/reference/syntax_and_semantics/literals/named_tuple.html