Hash
8 methodsA Hash maps each of its unique keys to a specific value, preserving insertion order since Ruby 1.9.
Hash#store(key, value) -> valueAssociates the given value with the given key. Equivalent to h[key] = value.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to set. |
| value | Object | Value to associate with key. |
Returns
Object
Example
h = {}
h.store(:a, 1)
h[:b] = 2
# h == {:a=>1, :b=>2}Hash#fetch(key, default=nil) -> valueReturns the value for the given key. If key not found, returns default or raises KeyError.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to look up. |
| default | Object | Default value if key is missing. |
Returns
Object
Example
h = {a: 1, b: 2}
h.fetch(:a) # 1
h.fetch(:c, 99) # 99
h.fetch(:c) { |k| "no #{k}" } # "no c"Hash#keys -> ArrayReturns a new array populated with the keys from this hash.
Returns
Array
Example
h = {a: 1, b: 2, c: 3}
h.keys # [:a, :b, :c]Hash#values -> ArrayReturns a new array populated with the values from this hash.
Returns
Array
Example
h = {a: 1, b: 2, c: 3}
h.values # [1, 2, 3]Hash#each {|key, value| block} -> HashCalls the block once for each key/value pair, passing key and value as parameters.
Returns
Hash
Example
{a: 1, b: 2}.each { |k, v| puts "#{k}=#{v}" }
# prints:
# a=1
# b=2Hash#size -> IntegerReturns the number of key-value pairs. Alias: length.
Returns
Integer
Example
{a: 1, b: 2, c: 3}.size # 3Hash#delete(key) -> valueDeletes the key-value pair and returns the value. Returns nil if key not found (or yields block).
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to delete. |
Returns
Object
Example
h = {a: 1, b: 2}
h.delete(:a) # 1
# h == {b: 2}Hash#has_key?(key) -> boolReturns true if the given key is present. Aliases: key?, member?, include?.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to check. |
Returns
Boolean
Example
h = {a: 1, b: 2}
h.has_key?(:a) # true
h.key?(:c) # false