Method: Array#to_h

Defined in:
array.c

#to_hObject #to_h {|item| ... } ⇒ Object

Returns a new Hash formed from self.

When a block is given, calls the block with each array element; the block must return a 2-element Array whose two elements form a key-value pair in the returned Hash:

a = ['foo', :bar, 1, [2, 3], {baz: 4}]
h = a.to_h {|item| [item, item] }
h # => {"foo"=>"foo", :bar=>:bar, 1=>1, [2, 3]=>[2, 3], {:baz=>4}=>{:baz=>4}}

When no block is given, self must be an Array of 2-element sub-arrays, each sub-array is formed into a key-value pair in the new Hash:

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

Overloads:

  • #to_h {|item| ... } ⇒ Object

    Yields:

    • (item)


2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
# File 'array.c', line 2950

static VALUE
rb_ary_to_h(VALUE ary)
{
    long i;
    VALUE hash = rb_hash_new_with_size(RARRAY_LEN(ary));
    int block_given = rb_block_given_p();

    for (i=0; i<RARRAY_LEN(ary); i++) {
	const VALUE e = rb_ary_elt(ary, i);
	const VALUE elt = block_given ? rb_yield_force_blockarg(e) : e;
	const VALUE key_value_pair = rb_check_array_type(elt);
	if (NIL_P(key_value_pair)) {
	    rb_raise(rb_eTypeError, "wrong element type %"PRIsVALUE" at %ld (expected array)",
		     rb_obj_class(elt), i);
	}
	if (RARRAY_LEN(key_value_pair) != 2) {
	    rb_raise(rb_eArgError, "wrong array length at %ld (expected 2, was %ld)",
		i, RARRAY_LEN(key_value_pair));
	}
	rb_hash_aset(hash, RARRAY_AREF(key_value_pair, 0), RARRAY_AREF(key_value_pair, 1));
    }
    return hash;
}