Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Enumerable#to_h
() -> ::Hash[untyped, untyped]
[T, U] () { (E) -> [ T, U ] } -> ::Hash[T, U]
to_h(*args) → hash
to_h(*args) {|element| ... } → hash
enum.c
View on GitHub ↗
static VALUE
enum_to_h(int argc, VALUE *argv, VALUE obj)
{
rb_block_call_func *iter = rb_block_given_p() ? enum_to_h_ii : enum_to_h_i;
return enum_hashify(obj, argc, argv, iter);
}
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.