Skip to content
instance method

Enumerable#to_h

() -> ::Hash[untyped, untyped]
[T, U] () { (Elem) -> [ T, U ] } -> ::Hash[T, U]
to_h(*args) → hash
to_h(*args) {|element| ... } → hash

When self consists of 2-element arrays, returns a hash each of whose entries is the key-value pair formed from one of those arrays:

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

When a block is given, the block is called with each element of self; the block should return a 2-element array which becomes a key-value pair in the returned hash:

Example
(0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}

Raises an exception if an element of self is not a 2-element array, and a block is not passed.

See also #to_a #to_set #tally #uniq also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0