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
See NamedTuple
literals in the language reference.
The compiler knows what types are in each key, so when indexing a named tuple with a symbol or string literal the compiler will return the value for that key and with the expected type, like in the above snippet. Indexing with a symbol or string literal for which there's no key will give a compile-time error.
Indexing with a symbol or string 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
.
Indexing with #[]?
does not make the return value nilable if the key is
known to exist:
language = {name: "Crystal", year: 2011}
language[:name]? # => "Crystal"
typeof(language[:name]?) # => String
NamedTuple
's own instance classes may also be indexed in a similar manner,
returning their value types instead:
tuple = NamedTuple(name: String, year: Int32)
tuple[:name] # => String
tuple["year"] # => Int32
tuple[:other]? # => nil
Included Modules
Defined in:
ray_tracer/color.crray_tracer/tuple.cr
Instance Method Summary
- #*(scalar : Float64)
- #*(scalar : Float32)
- #*(other : COLOR)
- #+(other : TUPLE)
- #+(other : COLOR)
- #-(other : TUPLE)
- #-(other : COLOR)
- #- : self
- #/(scalar : Float64)
- #/(scalar : Float32)
- #abs
- #b
- #cross(other : TUPLE)
- #dot(other : TUPLE)
- #g
- #magnitude
- #normalize
- #point?
- #r
- #reflect(normal : TUPLE)
- #vector?
- #w
- #x
- #y
- #z
Instance methods inherited from module RayTracer::Color
abs(c : COLOR)
abs,
add(c1 : COLOR, c2 : COLOR)
add,
color(r : Float32, g : Float32, b : Float32)color(h : Int32) color, divide(c : COLOR, s : Float32) divide, multiply(c : COLOR, s : Float32)
multiply(c1 : COLOR, c2 : COLOR) multiply, subtract(c1 : COLOR, c2 : COLOR) subtract
Instance methods inherited from module RayTracer::Tuple
add(a1 : TUPLE, a2 : TUPLE)
add,
cross(a1 : TUPLE, a2 : TUPLE)
cross,
divide(a : TUPLE, s : Float64)
divide,
dot(a1 : TUPLE, a2 : TUPLE)
dot,
magnitude(a : TUPLE)
magnitude,
multiply(a : TUPLE, s : Float64)
multiply,
negate(a : TUPLE)
negate,
normalize(a : TUPLE)
normalize,
point(x : Float64, y : Float64, z : Float64)
point,
point?(tuple : TUPLE)
point?,
reflect(v : TUPLE, n : TUPLE)
reflect,
subtract(a1 : TUPLE, a2 : TUPLE)
subtract,
tuple(x : Float64, y : Float64, z : Float64, w : Float64)tuple(vals : Array(Float64)) tuple, vector(x : Float64, y : Float64, z : Float64) vector, vector?(tuple : TUPLE) vector?