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
hash.c
View on GitHub ↗
static VALUE
rb_hash_to_h(VALUE hash)
{
if (rb_block_given_p()) {
return rb_hash_to_h_block(hash);
}
if (rb_obj_class(hash) != rb_cHash) {
const VALUE flags = RBASIC(hash)->flags;
hash = hash_dup(hash, rb_cHash, flags & RHASH_PROC_DEFAULT, RHASH_SIZE(hash));
}
return 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.