Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Hash#to_h

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

For an instance of Hash, returns self.

For a subclass of Hash, returns a new Hash containing the content of self.

When a block is given, returns a new Hash object whose content is based on the block; the block should return a 2-element Array object specifying the key-value pair to be included in the returned Array:

Example
h = {foo: 0, bar: 1, baz: 2}
h1 = h.to_h {|key, value| [value, key] }
h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
See also #to_a #to_hash #store #to_proc also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0