Skip to content

Ruby Hash API

Ruby's Hash — a dictionary mapping unique keys to values, preserving insertion order.

1 class · 8 methods

Hash

8 methods

A Hash maps each of its unique keys to a specific value, preserving insertion order since Ruby 1.9.

Hash#store(key, value) -> value

Associates the given value with the given key. Equivalent to h[key] = value.

Parameters

NameTypeDescription
keyObjectKey to set.
valueObjectValue to associate with key.

Returns

Object

Example

ruby
h = {}
h.store(:a, 1)
h[:b] = 2
# h == {:a=>1, :b=>2}
Hash#fetch(key, default=nil) -> value

Returns the value for the given key. If key not found, returns default or raises KeyError.

Parameters

NameTypeDescription
keyObjectKey to look up.
defaultObjectDefault value if key is missing.

Returns

Object

Example

ruby
h = {a: 1, b: 2}
h.fetch(:a)         # 1
h.fetch(:c, 99)     # 99
h.fetch(:c) { |k| "no #{k}" }  # "no c"
Hash#keys -> Array

Returns a new array populated with the keys from this hash.

Returns

Array

Example

ruby
h = {a: 1, b: 2, c: 3}
h.keys  # [:a, :b, :c]
Hash#values -> Array

Returns a new array populated with the values from this hash.

Returns

Array

Example

ruby
h = {a: 1, b: 2, c: 3}
h.values  # [1, 2, 3]
Hash#each {|key, value| block} -> Hash

Calls the block once for each key/value pair, passing key and value as parameters.

Returns

Hash

Example

ruby
{a: 1, b: 2}.each { |k, v| puts "#{k}=#{v}" }
# prints:
# a=1
# b=2
Hash#size -> Integer

Returns the number of key-value pairs. Alias: length.

Returns

Integer

Example

ruby
{a: 1, b: 2, c: 3}.size  # 3
Hash#delete(key) -> value

Deletes the key-value pair and returns the value. Returns nil if key not found (or yields block).

Parameters

NameTypeDescription
keyObjectKey to delete.

Returns

Object

Example

ruby
h = {a: 1, b: 2}
h.delete(:a)  # 1
# h == {b: 2}
Hash#has_key?(key) -> bool

Returns true if the given key is present. Aliases: key?, member?, include?.

Parameters

NameTypeDescription
keyObjectKey to check.

Returns

Boolean

Example

ruby
h = {a: 1, b: 2}
h.has_key?(:a)  # true
h.key?(:c)      # false