Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns a new Hash object containing the entries for the given keys:
h = {foo: 0, bar: 1, baz: 2}
h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
Any given keys that are not found are ignored.
               static VALUE
rb_hash_slice(int argc, VALUE *argv, VALUE hash)
    int i;
    VALUE key, value, result;

    if (argc == 0 || RHASH_EMPTY_P(hash)) {
        return copy_compare_by_id(rb_hash_new(), hash);
    result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);

    for (i = 0; i < argc; i++) {
        key = argv[i];
        value = rb_hash_lookup2(hash, key, Qundef);
        if (value != Qundef)
            rb_hash_aset(result, key, value);

    return result;

Was this page useful?