Skip to content

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

instance method

Array#to_h

() -> ::Hash[untyped, untyped]
[K, V] () { (Elem element) -> ::Hash::_Pair[K, V] } -> ::Hash[K, V]
to_h → new_hash
to_h {|element| ... } → new_hash

Returns a new hash formed from self.

With no block given, each element of self must be a 2-element sub-array; forms each sub-array into a key-value pair in the new hash:

Example
a = [['foo', 'zero'], ['bar', 'one'], ['baz', 'two']]
a.to_h # => {"foo" => "zero", "bar" => "one", "baz" => "two"}
[].to_h # => {}

With a block given, the block must return a 2-element array; calls the block with each element of self; forms each returned array into a key-value pair in the returned hash:

Example
a = ['foo', :bar, 1, [2, 3], {baz: 4}]
a.to_h {|element| [element, element.class] }
# => {"foo" => String, bar: Symbol, 1 => Integer, [2, 3] => Array, {baz: 4} => Hash}

Related: see Methods for Converting.

See also #to_ary #to_s #to_a #transpose also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0