Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#to_h

to_h → hash
to_h {|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 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0