NamedTuple

struct NamedTuple(**T)

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:

named_tuple.cr
json/to_json.cr
yaml/to_yaml.cr

Class Method Summary

Instance Method Summary

Class Method Detail

def self.from(hash : Hash)Source

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)Source

def self.new(pull : YAML::PullParser)Source

def self.newSource

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)Source

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)Source

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)Source

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)Source

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 cloneSource

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

def each(&block) : NilSource

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) : NilSource

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) : NilSource

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)Source

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?Source

Returns true if this named tuple is empty.

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

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

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)Source

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)Source

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)Source

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) : BoolSource

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) : BoolSource

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 hashSource

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

See also: Object#hash.

def inspectSource

Same as #to_s.

def keysSource

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

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

def map(&block)Source

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)Source

def sizeSource

Returns the number of elements in this named tuple.

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

def to_aSource

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_hSource

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)Source

def to_s(io)Source

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)Source

def valuesSource

Returns a Tuple with the values in this named tuple.

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

© 2012–2017 Manas Technology Solutions.
Licensed under the Apache License, Version 2.0.
https://crystal-lang.org/api/0.22.0/NamedTuple.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部