Method: Hash.[]

Defined in:
hash.c

+ (Object) [](key, value, ...) + (Object) []([ [key, value)) + (Object) [](object)

Creates a new hash populated with the given objects. Equivalent to the literal { key => value, ... }. In the first form, keys and values occur in pairs, so there must be an even number of arguments. The second and third form take a single argument which is either an array of key-value pairs or an object convertible to a hash.

Hash["a", 100, "b", 200]             #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ]   #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200]         #=> {"a"=>100, "b"=>200}


# File 'hash.c'

/*
 *  call-seq:
 *     Hash[ key, value, ... ]         -> new_hash
 *     Hash[ [ [key, value], ... ] ]   -> new_hash
 *     Hash[ object ]                  -> new_hash
 *
 *  Creates a new hash populated with the given objects. Equivalent to
 *  the literal <code>{ <i>key</i> => <i>value</i>, ... }</code>. In the first
 *  form, keys and values occur in pairs, so there must be an even number of arguments.
 *  The second and third form take a single argument which is either
 *  an array of key-value pairs or an object convertible to a hash.
 *
 *     Hash["a", 100, "b", 200]             #=> {"a"=>100, "b"=>200}
 *     Hash[ [ ["a", 100], ["b", 200] ] ]   #=> {"a"=>100, "b"=>200}
 *     Hash["a" => 100, "b" => 200]         #=> {"a"=>100, "b"=>200}
 */

static VALUE
rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
{
    VALUE hash, tmp;
    int i;

    if (argc == 1) {
    tmp = rb_hash_s_try_convert(Qnil, argv[0]);
    if (!NIL_P(tmp)) {
        hash = hash_alloc(klass);
        if (RHASH(tmp)->ntbl) {
        RHASH(hash)->ntbl = st_copy(RHASH(tmp)->ntbl);
        }
        return hash;
    }

    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 v = rb_check_array_type(RARRAY_PTR(tmp)[i]);
        VALUE key, val = Qnil;

        if (NIL_P(v)) continue;
        switch (RARRAY_LEN(v)) {
          case 2:
            val = RARRAY_PTR(v)[1];
          case 1:
            key = RARRAY_PTR(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);
    for (i=0; i<argc; i+=2) {
        rb_hash_aset(hash, argv[i], argv[i + 1]);
    }

    return hash;
}

Comments