summaryrefslogtreecommitdiff
path: root/hash.c
diff options
context:
space:
mode:
authorglass <glass@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2017-10-21 06:08:33 (GMT)
committerglass <glass@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2017-10-21 06:08:33 (GMT)
commit6c50bdda0b33f8031e54e3ea7857de43da821ead (patch)
treeb9d944adb4640fdb92497cb65964e9b6fb46c6a9 /hash.c
parentd83f9745f5f4e3ed8cc0ce2b47c6dfbef498e42f (diff)
hash.c: Add Hash#slice
* hash.c (rb_hash_slice): add Hash#slice [Feature #8499] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60229 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'hash.c')
-rw-r--r--hash.c33
1 files changed, 33 insertions, 0 deletions
diff --git a/hash.c b/hash.c
index 878e215..6e9cda9 100644
--- a/hash.c
+++ b/hash.c
@@ -1325,6 +1325,38 @@ rb_hash_reject(VALUE hash)
}
/*
+ * call-seq:
+ * hsh.slice -> a_hash
+ *
+ * Slices a hash to include only the given keys.
+ * Returns a hash containing the given keys.
+ *
+ * h = { "a" => 100, "b" => 200, "c" => 300 }
+ * h.slice("a") #=> {"a" => 100}
+ */
+
+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 rb_hash_new();
+ }
+ result = rb_hash_new_with_size(argc);
+
+ 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;
+}
+
+/*
* call-seq:
* hsh.values_at(key, ...) -> array
*
@@ -4585,6 +4617,7 @@ Init_Hash(void)
rb_define_method(rb_cHash, "select!", rb_hash_select_bang, 0);
rb_define_method(rb_cHash, "reject", rb_hash_reject, 0);
rb_define_method(rb_cHash, "reject!", rb_hash_reject_bang, 0);
+ rb_define_method(rb_cHash, "slice", rb_hash_slice, -1);
rb_define_method(rb_cHash, "clear", rb_hash_clear, 0);
rb_define_method(rb_cHash, "invert", rb_hash_invert, 0);
rb_define_method(rb_cHash, "update", rb_hash_update, 1);