Hash.[]
static VALUE
rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
{
VALUE hash, tmp;
if (argc == 1) {
tmp = rb_hash_s_try_convert(Qnil, argv[0]);
if (!NIL_P(tmp)) {
if (!RHASH_EMPTY_P(tmp) && rb_hash_compare_by_id_p(tmp)) {
/* hash_copy for non-empty hash will copy compare_by_identity
flag, but we don't want it copied. Work around by
converting hash to flattened array and using that. */
tmp = rb_hash_to_a(tmp);
}
else {
hash = hash_alloc(klass);
if (!RHASH_EMPTY_P(tmp))
hash_copy(hash, tmp);
return hash;
}
}
else {
tmp = rb_check_array_type(argv[0]);
}
if (!NIL_P(tmp)) {
long i;
hash = hash_alloc(klass);
for (i = 0; i < RARRAY_LEN(tmp); ++i) {
VALUE e = RARRAY_AREF(tmp, i);
VALUE v = rb_check_array_type(e);
VALUE key, val = Qnil;
if (NIL_P(v)) {
rb_raise(rb_eArgError, "wrong element type %s at %ld (expected array)",
rb_builtin_class_name(e), i);
}
switch (RARRAY_LEN(v)) {
default:
rb_raise(rb_eArgError, "invalid number of elements (%ld for 1..2)",
RARRAY_LEN(v));
case 2:
val = RARRAY_AREF(v, 1);
case 1:
key = RARRAY_AREF(v, 0);
rb_hash_aset(hash, key, val);
}
}
return hash;
}
}
if (argc % 2 != 0) {
rb_raise(rb_eArgError, "odd number of arguments for Hash");
}
hash = hash_alloc(klass);
rb_hash_bulk_insert(argc, argv, hash);
hash_verify(hash);
return hash;
}
Returns a new Hash object populated with the given objects, if any. See Hash::new.
With no argument given, returns a new empty hash.
With a single argument other_hash given that is a hash, returns a new hash initialized with the entries from that hash (but not with its default or default_proc):
h = {foo: 0, bar: 1, baz: 2} Hash[h] # => {foo: 0, bar: 1, baz: 2}
With a single argument 2_element_arrays given that is an array of 2-element arrays, returns a new hash wherein each given 2-element array forms a key-value entry:
Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {foo: 0, bar: 1}
With an even number of arguments objects given, returns a new hash wherein each successive pair of arguments is a key-value entry:
Hash[:foo, 0, :bar, 1] # => {foo: 0, bar: 1}
Raises ArgumentError if the argument list does not conform to any of the above.
See also Methods for Creating a Hash.