Skip to content
class method

Hash.[]

[U, V] (::_ToHash[U, V]) -> ::Hash[U, V]
[U, V] (::Array[[ U, V ]]) -> ::Hash[U, V]
(*untyped) -> ::Hash[untyped, untyped]
Hash[] → new_empty_hash
Hash[other_hash] → new_hash
Hash[ [*2_element_arrays] ] → new_hash
Hash[*objects] → new_hash

Returns a new Hash object populated with the given objects, if any. See Hash::new.

With no argument given, returns a new empty hash.

With a single argument other_hash given that is a hash, returns a new hash initialized with the entries from that hash (but not with its default or default_proc):

Example
h = {foo: 0, bar: 1, baz: 2}
Hash[h] # => {foo: 0, bar: 1, baz: 2}

With a single argument 2_element_arrays given that is an array of 2-element arrays, returns a new hash wherein each given 2-element array forms a key-value entry:

Example
Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {foo: 0, bar: 1}

With an even number of arguments objects given, returns a new hash wherein each successive pair of arguments is a key-value entry:

Example
Hash[:foo, 0, :bar, 1] # => {foo: 0, bar: 1}

Raises ArgumentError if the argument list does not conform to any of the above.

See also Methods for Creating a Hash.

See also #[] #[]= .new .ruby2_keywords_hash also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0