- README

- Top Level Namespace
- Adler32
- ArgumentError
- Array
- Atomic
- Base64
  - Error
- Benchmark
  - BM
    - Job
    - Tms
  - IPS
    - Entry
    - Job
- BigFloat
- BigInt
- BigRational
- BitArray
- Bool
- Box
- Bytes
- Channel
  - Buffered
  - ClosedError
  - ReceiveAction
  - SelectAction
  - SendAction
  - Unbuffered
- Char
  - Reader
- Class
- Colorize
  - Object
  - ObjectExtensions
- Comparable
- Complex
- Concurrent
  - CanceledError
- CRC32
- Crypto
  - Bcrypt
    - Error
    - Password
  - Blowfish
  - Subtle
- CSV
  - Builder
    - Row
  - Error
  - Lexer
  - MalformedCSVError
  - Parser
  - Row
  - Token
    - Kind
- Debug
  - DWARF
    - Abbrev
      - Attribute
    - AT
    - FORM
    - Info
      - Value
    - LineNumbers
      - Register
      - Row
      - Sequence
    - LNE
    - LNS
    - Strings
    - TAG
  - ELF
    - Endianness
    - Error
    - Ident
    - Klass
    - Machine
    - OSABI
    - SectionHeader
      - Flags
      - Type
    - Type
- Deque
- Digest
  - Base
  - MD5
  - SHA1
- Dir
- DivisionByZero
- DL
- ECR
- Enum
- Enumerable
  - EmptyError
- ENV
- Errno
- Exception
- Fiber
- File
  - Stat
- FileUtils
- Flate
  - Error
  - Reader
  - Strategy
  - Writer
- Float
  - Primitive
- Float32
- Float64
- GC
  - Stats
- Gzip
  - Error
  - Header
  - Reader
  - Writer
- Hash
- HTML
- HTTP
  - Client
    - BodyType
    - Response
  - CompressHandler
  - ComputedContentTypeHeader
  - Cookie
  - Cookies
  - ErrorHandler
  - FormData
    - Builder
    - Error
    - FileMetadata
    - Parser
    - Part
  - Handler
    - Proc
  - Headers
  - LogHandler
  - Multipart
    - Builder
    - Error
    - Parser
  - Params
    - Builder
  - Request
  - Server
    - Context
    - RequestProcessor
    - Response
  - StaticFileHandler
    - DirectoryListing
  - WebSocket
  - WebSocketHandler
- Indexable
- IndexError
- INI
- Int
  - Primitive
  - Signed
  - Unsigned
- Int16
- Int32
- Int64
- Int8
- InvalidByteSequenceError
- IO
  - Buffered
  - ByteFormat
    - BigEndian
    - LittleEndian
    - NetworkEndian
    - SystemEndian
  - Delimited
  - EncodingOptions
  - EOFError
  - Error
  - FileDescriptor
  - Hexdump
  - Memory
  - MultiWriter
  - Seek
  - Sized
  - Timeout
- IPSocket
- Iterable
- Iterator
  - IteratorWrapper
  - Stop
- JSON
  - Any
  - Builder
    - ArrayState
    - DocumentEndState
    - DocumentStartState
    - ObjectState
    - StartState
    - State
  - Error
  - Lexer
  - ParseException
  - Parser
  - PullParser
  - Token
  - Type
- KeyError
- Levenshtein
  - Finder
- LLVM
  - ABI
    - AArch64
    - ArgKind
    - ArgType
    - ARM
    - FunctionType
    - X86
    - X86_64
      - RegClass
  - AtomicOrdering
  - AtomicRMWBinOp
  - Attribute
  - AttributeIndex
  - BasicBlock
  - BasicBlockCollection
  - Builder
  - CallConvention
  - CodeGenFileType
  - CodeGenOptLevel
  - CodeModel
  - Context
  - DIBuilder
  - DIFlags
  - DwarfTag
  - DwarfTypeEncoding
  - Function
  - FunctionCollection
  - FunctionPassManager
    - Runner
  - GenericValue
  - GlobalCollection
  - InstructionCollection
  - IntPredicate
  - JITCompiler
  - Linkage
  - MemoryBuffer
  - Module
  - ModuleFlag
  - ModulePassManager
  - ParameterCollection
  - PassManagerBuilder
  - PassRegistry
  - PhiTable
  - RealPredicate
  - RelocMode
  - Target
  - TargetData
  - TargetMachine
  - Type
    - Kind
  - Value
    - Kind
  - ValueMethods
  - VerifierFailureAction
- Logger
  - Formatter
  - Severity
- Markdown
  - HTMLRenderer
  - Parser
    - PrefixHeader
    - UnorderedList
  - Renderer
- Math
- Mutex
- NamedTuple
- Nil
- Number
  - Primitive
- OAuth
  - AccessToken
  - Consumer
  - Error
  - RequestToken
- OAuth2
  - AccessToken
    - Bearer
    - Mac
  - Client
  - Error
  - Session
- Object
- OpenSSL
  - Digest
    - Error
    - UnsupportedError
  - DigestBase
  - Error
  - HMAC
  - MD5
  - SHA1
  - SSL
    - Context
      - Client
      - Server
    - Error
    - ErrorType
    - Modes
    - Options
    - Socket
      - Client
      - Server
    - VerifyMode
    - X509VerifyFlags
- OptionParser
  - Exception
  - InvalidOption
  - MissingOption
- PartialComparable
- Pointer
  - Appender
- PrettyPrint
- Proc
- Process
  - Env
  - Status
  - Stdio
  - Tms
- Random
  - MT19937
- Range
- Readline
  - CompletionProc
  - KeyBindingProc
- Reference
- Reflect
- Regex
  - MatchData
  - Options
- SecureRandom
- Set
- Signal
- Slice
- Socket
  - Address
  - Addrinfo
  - Error
  - Family
  - IPAddress
  - Protocol
  - Server
  - Type
  - UNIXAddress
- Spec
  - Expectations
  - Methods
  - ObjectExtensions
- StaticArray
- String
  - Builder
  - RawConverter
- StringPool
- StringScanner
- Struct
- Symbol
- System
- TCPServer
- TCPSocket
- Tempfile
- Termios
  - AttributeSelection
  - BaudRate
  - ControlMode
  - InputMode
  - LineControl
  - LocalMode
  - OutputMode
- Time
  - DayOfWeek
  - EpochConverter
  - EpochMillisConverter
  - Format
    - Error
  - Kind
  - MonthSpan
  - Span
- Tuple
- TypeCastError
- UDPSocket
- UInt16
- UInt32
- UInt64
- UInt8
- Unicode
  - CaseOptions
- Union
- UNIXServer
- UNIXSocket
- URI
  - Error
- Value
- WeakRef
- XML
  - Attributes
  - AttributeType
  - Builder
  - Error
  - HTMLParserOptions
  - Namespace
  - Node
  - NodeSet
  - ParserOptions
  - Reader
  - SaveOptions
  - Type
  - XPathContext
- YAML
  - Any
  - Builder
  - Error
  - EventKind
  - ParseException
  - Parser
  - PullParser
  - Type
- Zip
  - CompressionMethod
  - Error
  - File
    - Entry
  - FileInfo
  - Reader
    - Entry
  - Writer
    - Entry
- Zlib
  - Error
  - Reader
  - Writer

# struct NamedTuple(**T)

- NamedTuple(**T)
- Value
- Object

## Overview

A named tuple is a fixed-size, immutable, stack-allocated mapping of a fixed set of keys to values.

You can think of a `NamedTuple` as an immutable `Hash` whose keys (which are of type `Symbol`), and the types for each key, are known at compile time.

A named tuple can be created with a named tuple literal:

    language = {name: "Crystal", year: 2011} # NamedTuple(name: String, year: Int32)

    language[:name]  # => "Crystal"
    language[:year]  # => 2011
    language[:other] # compile time error

The compiler knows what types are in each key, so when indexing a named tuple with a symbol literal the compiler will return the value for that key and with the expected type, like in the above snippet. Indexing with a symbol literal for which there's no key will give a compile-time error.

Indexing with a symbol that is only known at runtime will return a value whose type is the union of all the types in the named tuple, and might raise `KeyError`.

## Defined in:

## Class Method Summary

- .from(hash : Hash)

  Creates a named tuple from the given hash, with elements casted to the given types.

- .new(pull : JSON::PullParser)
- .new(pull : YAML::PullParser)
- .new

  Creates a named tuple that will contain the given arguments.

## Instance Method Summary

- #==(other : NamedTuple)

  Returns `true` if this tuple has the same keys as other, and values for each key are the same in `self` and other.

- #==(other : self)

  Returns `true` if this tuple has the same keys as other, and values for each key are the same in `self` and other.

- #[](key : Symbol | String)

  Returns the value for the given key, if there's such key, otherwise raises `KeyError`.

- #[]?(key : Symbol | String)

  Returns the value for the given key, if there's such key, otherwise returns `nil`.

- #clone

  Returns a named tuple with the same keys but with cloned values, using the `#clone` method.

- #each(&block) : Nil

  Yields each key and value in this named tuple.

- #each_key(&block) : Nil

  Yields each key in this named tuple.

- #each_value(&block) : Nil

  Yields each value in this named tuple.

- #each_with_index(offset = 0, &block)

  Yields each key and value, together with an index starting at offset, in this named tuple.

- #empty?

  Returns `true` if this named tuple is empty.

- #fetch(key : Symbol | String, default_value)

  Returns the value for the given key, if there's such key, otherwise returns default_value.

- #fetch(key : Symbol, &block)

  Returns the value for the given key, if there's such key, otherwise the value returned by the block.

- #fetch(key : String, &block)

  Returns the value for the given key, if there's such key, otherwise the value returned by the block.

- #from(hash : Hash)

  Expects to be called on a named tuple whose values are types, creates a tuple from the given hash, with types casted appropriately.

- #has_key?(key : String) : Bool

  Returns `true` if this named tuple has the given key, `false` otherwise.

- #has_key?(key : Symbol) : Bool

  Returns `true` if this named tuple has the given key, `false` otherwise.

- #hash

  Returns a hash value based on this name tuple's size, keys and values.

- #inspect

  Same as `#to_s`.

- #keys

  Returns a `Tuple` of symbols with the keys in this named tuple.

- #map(&block)

  Returns an `Array` populated with the results of each iteration in the given block, which is given each key and value in this named tuple.

- #pretty_print(pp)
- #size

  Returns the number of elements in this named tuple.

- #to_a

  Returns a new `Array` of tuples populated with each key-value pair.

- #to_h

  Returns a `Hash` with the keys and values in this named tuple.

- #to_json(json : JSON::Builder)
- #to_s(io)

  Appends a string representation of this named tuple to the given `IO`.

- #to_yaml(yaml : YAML::Builder)
- #values

  Returns a `Tuple` with the values in this named tuple.

### Instance methods inherited from struct `Value`

==(other) ==, dup dup

### Instance methods inherited from class `Object`

!=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other) ===, =~(other) =~, class class, dup dup, hash hash, inspect(io : IO)
inspect inspect, itself itself, not_nil! not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, tap(&block) tap, to_json(io : IO)
to_json to_json, to_pretty_json(indent : String = " ")
to_pretty_json(io : IO, indent : String = " ") to_pretty_json, to_s
to_s(io : IO) to_s, to_yaml(io : IO)
to_yaml to_yaml, try(&block) try

### Class methods inherited from class `Object`

from_json(string_or_io, root : String) : self
from_json(string_or_io) : self from_json, from_yaml(string_or_io) : self from_yaml

## Class Method Detail

def self.from(hash : Hash) #

Creates a named tuple from the given hash, with elements casted to the given types. Here the Int32 | String union is cast to Int32.

    num_or_str = 42.as(Int32 | String)
    NamedTuple(name: String, val: Int32).from({"name" => "number", "val" => num_or_str}) # => {name: "number", val: 42}

    num_or_str = "a string".as(Int32 | String)
    NamedTuple(name: String, val: Int32).from({"name" => "number", "val" => num_or_str}) # raises TypeCastError (cast from String to Int32 failed)

See also: `#from`.

def self.new(pull : JSON::PullParser) #
def self.new(pull : YAML::PullParser) #
def self.new #

Creates a named tuple that will contain the given arguments.

This method is useful in macros and generic code because with it you can creates empty named tuples, something that you can't do with a tuple literal.

    NamedTuple.new(name: "Crystal", year: 2011) #=> {name: "Crystal", year: 2011}
    NamedTuple.new # => {}
    {}             # syntax error

## Instance Method Detail

def ==(other : NamedTuple) #

Returns `true` if this tuple has the same keys as other, and values for each key are the same in `self` and other.

    tuple1 = {name: "Crystal", year: 2011}
    tuple2 = {year: 2011, name: "Crystal"}
    tuple3 = {name: "Crystal", year: 2012}
    tuple4 = {name: "Crystal", year: 2011.0}

    tuple1 == tuple2 # => true
    tuple1 == tuple3 # => false
    tuple1 == tuple4 # => true

def ==(other : self) #

Returns `true` if this tuple has the same keys as other, and values for each key are the same in `self` and other.

    tuple1 = {name: "Crystal", year: 2011}
    tuple2 = {year: 2011, name: "Crystal"}
    tuple3 = {name: "Crystal", year: 2012}
    tuple4 = {name: "Crystal", year: 2011.0}

    tuple1 == tuple2 # => true
    tuple1 == tuple3 # => false
    tuple1 == tuple4 # => true

def [](key : Symbol | String) #

Returns the value for the given key, if there's such key, otherwise raises `KeyError`.

    tuple = {name: "Crystal", year: 2011}

    key = :name
    tuple[key] # => "Crystal"

    key = "year"
    tuple[key] # => 2011

    key = :other
    tuple[key] # raises KeyError

def []?(key : Symbol | String) #

Returns the value for the given key, if there's such key, otherwise returns `nil`.

    tuple = {name: "Crystal", year: 2011}

    key = :name
    tuple[key]? # => "Crystal"

    key = "year"
    tuple[key] # => 2011

    key = :other
    tuple[key]? # => nil

def clone #

Returns a named tuple with the same keys but with cloned values, using the `#clone` method.

def each(&block) : Nil #

Yields each key and value in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.each do |key, value|
      puts "#{key} = #{value}"
    end

Output:

    name = Crystal
    year = 2011

def each_key(&block) : Nil #

Yields each key in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.each_key do |key|
      puts key
    end

Output:

    name
    year

def each_value(&block) : Nil #

Yields each value in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.each_value do |value|
      puts value
    end

Output:

    Crystal
    2011

def each_with_index(offset = 0, &block) #

Yields each key and value, together with an index starting at offset, in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.each_with_index do |key, value, i|
      puts "#{i + 1}) #{key} = #{value}"
    end

Output:

    1) name = Crystal
    2) year = 2011

def empty? #

Returns `true` if this named tuple is empty.

    tuple = {name: "Crystal", year: 2011}
    tuple.empty? # => false

def fetch(key : Symbol | String, default_value) #

Returns the value for the given key, if there's such key, otherwise returns default_value.

    tuple = {name: "Crystal", year: 2011}
    tuple.fetch(:name, "Unknown") # => "Crystal"
    tuple.fetch("year", 0)        # => 2011
    tuple.fetch(:other, 0)        # => 0

def fetch(key : Symbol, &block) #

Returns the value for the given key, if there's such key, otherwise the value returned by the block.

    tuple = {name: "Crystal", year: 2011}
    tuple.fetch(:name) { "Unknown" } # => "Crystal"
    tuple.fetch(:other) { 0 }        # => 0

def fetch(key : String, &block) #

Returns the value for the given key, if there's such key, otherwise the value returned by the block.

    tuple = {name: "Crystal", year: 2011}
    tuple.fetch("name") { "Unknown" } # => "Crystal"
    tuple.fetch("other") { 0 }        # => 0

def from(hash : Hash) #

Expects to be called on a named tuple whose values are types, creates a tuple from the given hash, with types casted appropriately. The hash keys must be either symbols or strings.

This allows you to easily pass a hash as individual named arguments to a method.

    require "json"

    def speak_about(thing : String, n : Int64)
      "I see #{n} #{thing}s"
    end

    data = JSON.parse(%({"thing": "world", "n": 2})).as_h
    speak_about(**{thing: String, n: Int64}.from(data)) # => "I see 2 worlds"

def has_key?(key : String) : Bool #

Returns `true` if this named tuple has the given key, `false` otherwise.

    tuple = {name: "Crystal", year: 2011}
    tuple.has_key?(:name)  # => true
    tuple.has_key?(:other) # => false

def has_key?(key : Symbol) : Bool #

Returns `true` if this named tuple has the given key, `false` otherwise.

    tuple = {name: "Crystal", year: 2011}
    tuple.has_key?(:name)  # => true
    tuple.has_key?(:other) # => false

def hash #

Returns a hash value based on this name tuple's size, keys and values.

See also: `Object#hash`.

def inspect #

Same as `#to_s`.

def keys #

Returns a `Tuple` of symbols with the keys in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.keys # => {:name, :year}

def map(&block) #

Returns an `Array` populated with the results of each iteration in the given block, which is given each key and value in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.map { |k, v| "#{k}: #{v}" } # => ["name: Crystal", "year: 2011"]

def pretty_print(pp) #
def size #

Returns the number of elements in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.size # => 2

def to_a #

Returns a new `Array` of tuples populated with each key-value pair.

    tuple = {name: "Crystal", year: 2011}
    tuple.to_a # => [{:name, "Crystal"}, {:year, 2011}]

def to_h #

Returns a `Hash` with the keys and values in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.to_h # => {:name => "Crystal", :year => 2011}

def to_json(json : JSON::Builder) #
def to_s(io) #

Appends a string representation of this named tuple to the given `IO`.

    tuple = {name: "Crystal", year: 2011}
    tuple.to_s # => %({name: "Crystal", year: 2011})

def to_yaml(yaml : YAML::Builder) #
def values #

Returns a `Tuple` with the values in this named tuple.

    tuple = {name: "Crystal", year: 2011}
    tuple.values # => {"Crystal", 2011}