Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Hash#to_h

() -> ::Hash[K, V]
[A, B] () { (K key, V value) -> ::Hash::_Pair[A, B] } -> ::Hash[A, B]
to_h {|key, value| ... } → new_hash
to_h → self or new_hash

With a block given, returns a new hash whose content is based on the block; the block is called with each entry’s key and value; the block should return a 2-element array containing the key and value to be included in the returned array:

Example
h = {foo: 0, bar: 1, baz: 2}
h.to_h {|key, value| [value, key] }
# => {0 => :foo, 1 => :bar, 2 => :baz}

With no block given, returns self if self is an instance of Hash; if self is a subclass of Hash, returns a new hash containing the content of self.

Related: see Methods for Converting.

See also #to_a #to_hash #store #to_proc also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0