summaryrefslogtreecommitdiff
path: root/hash.c
diff options
context:
space:
mode:
authornobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2018-04-19 05:55:42 (GMT)
committernobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2018-04-19 05:55:42 (GMT)
commit9760a7f905367e96d6c22bbace1680d694fa16bd (patch)
tree39abec463772c7f6f1b67278fe409888d4b091fa /hash.c
parent55d3ed4b9d43beff4b905c9c3d853770203dd0b7 (diff)
Add slice method to ENV like Hash#slice
[Feature #14559] From: Benoit Tigeot <benoit@hopsandfork.com> git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@63188 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'hash.c')
-rw-r--r--hash.c30
1 files changed, 30 insertions, 0 deletions
diff --git a/hash.c b/hash.c
index 3a49987..c8125a0 100644
--- a/hash.c
+++ b/hash.c
@@ -4068,6 +4068,35 @@ env_keep_if(VALUE ehash)
}
/*
+ * call-seq:
+ * ENV.slice(*keys) -> a_hash
+ *
+ * Returns a hash containing only the given keys from ENV and their values.
+ *
+ * ENV.slice("TERM","HOME") #=> {"TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
+ */
+static VALUE
+env_slice(int argc, VALUE *argv)
+{
+ int i;
+ VALUE key, value, result;
+
+ if (argc == 0) {
+ return rb_hash_new();
+ }
+ result = rb_hash_new_with_size(argc);
+
+ for (i = 0; i < argc; i++) {
+ key = argv[i];
+ value = rb_f_getenv(Qnil, key);
+ if (value != Qnil)
+ rb_hash_aset(result, key, value);
+ }
+
+ return result;
+}
+
+/*
* call-seq:
* ENV.clear
*
@@ -4749,6 +4778,7 @@ Init_Hash(void)
rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
+ rb_define_singleton_method(envtbl, "slice", env_slice, -1);
rb_define_singleton_method(envtbl, "clear", rb_env_clear, 0);
rb_define_singleton_method(envtbl, "reject", env_reject, 0);
rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);