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.

Tags

crystal