From 32acadf7572a79e55c4f6f5c64ad0e2cd7aa5c7a Mon Sep 17 00:00:00 2001 From: Benoit Tigeot Date: Wed, 21 Mar 2018 11:46:30 +0000 Subject: [PATCH] Add slice method to ENV like Hash#slice --- hash.c | 30 ++++++++++++++++++++++++++++++ test/ruby/test_env.rb | 11 +++++++++++ 2 files changed, 41 insertions(+) diff --git a/hash.c b/hash.c index 3a499872ad73..c8125a0d6cc6 100644 --- a/hash.c +++ b/hash.c @@ -4067,6 +4067,35 @@ env_keep_if(VALUE ehash) return envtbl; } +/* + * 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); diff --git a/test/ruby/test_env.rb b/test/ruby/test_env.rb index 699f7db084be..2f4923fbd95a 100644 --- a/test/ruby/test_env.rb +++ b/test/ruby/test_env.rb @@ -281,6 +281,17 @@ def test_filter end end + def test_slice + ENV.clear + ENV["foo"] = "bar" + ENV["baz"] = "qux" + ENV["bar"] = "rab" + assert_equal({}, ENV.slice()) + assert_equal({}, ENV.slice("")) + assert_equal({}, ENV.slice("unknown")) + assert_equal({"foo"=>"bar", "baz"=>"qux"}, ENV.slice("foo", "baz")) + end + def test_clear ENV.clear assert_equal(0, ENV.size)