struct Tuple(*T)
- Tuple(*T)
- Value
- Object
Overview
A tuple is a fixed-size, immutable, stack-allocated sequence of values of possibly different types.
You can think of a Tuple
as an immutable Array
whose types for each position
are known at compile time.
A tuple can be created with the usual new
method or with a tuple literal:
tuple = {1, "hello", 'x'} # Tuple(Int32, String, Char)
tuple[0] # => 1
tuple[1] # => "hello"
tuple[2] # => 'x'
The compiler knows what types are in each position, so when indexing a tuple with an integer literal the compiler will return the value in that index and with the expected type, like in the above snippet. Indexing with an integer literal outside the bounds of the tuple will give a compile-time error.
Indexing with an integer value that is only known at runtime will return
a value whose type is the union of all the types in the tuple, and might raise
IndexError
.
Tuples are the preferred way to return fixed-size multiple return values because no memory is needed to be allocated for them:
def one_and_hello
{1, "hello"}
end
one, hello = one_and_hello
one # => 1
hello # => "hello"
Good examples of the above are Number#divmod
and Enumerable#minmax
.
Tuples can be splat with the *
operator and passed to methods:
def multiply(string, value)
string * value
end
tuple = {"hey", 2}
value = multiply(*tuple) # same as multiply tuple[0], tuple[1]
value # => "heyhey"
Finally, when using a splat argument in a method definition its type will be a tuple of the call arguments:
def splat_test(*args)
args
end
tuple = splat_test 1, "hello", 'x'
tuple.class # => Tuple(Int32, String, Char)
tuple # => {1, "hello", 'x'}
Included Modules
Defined in:
tuple/each_product.crtuple/times.cr
tuple/get.cr
Instance Method Summary
Macro Summary
Instance methods inherited from module Comparable(Tuple(*T))
max(x : T)
max,
min(x : T)
min
Instance methods inherited from module Indexable(Union(*T))
[](point : Point)
[],
[]?(point : Point)
[]?,
each_pair(&)each_pair each_pair, fetch(point : Point, &) fetch
Instance methods inherited from module Enumerable(Union(*T))
accumulate(init : U) : Array(U) forall Uaccumulate : Array(Union(T))
accumulate(init : U, &block : U, Union(T) -> U) : Array(U) forall U
accumulate(&block : Union(T), Union(T) -> Union(T)) : Array(Union(T)) accumulate, mex : Union(T) mex, mex_sorted : Union(T) mex_sorted, tally(*, default : Int32) : Hash(Union(T), Int32) tally, unique : self
unique(&) : self unique