[前][次][番号順一覧][スレッド一覧]

ruby-changes:50981

From: nobu <ko1@a...>
Date: Thu, 19 Apr 2018 14:55:47 +0900 (JST)
Subject: [ruby-changes:50981] nobu:r63188 (trunk): Add slice method to ENV like Hash#slice

nobu	2018-04-19 14:55:42 +0900 (Thu, 19 Apr 2018)

  New Revision: 63188

  https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=63188

  Log:
    Add slice method to ENV like Hash#slice
    
    [Feature #14559]
    
    From:    Benoit Tigeot <benoit@h...>

  Modified files:
    trunk/hash.c
    trunk/test/ruby/test_env.rb
Index: test/ruby/test_env.rb
===================================================================
--- test/ruby/test_env.rb	(revision 63187)
+++ test/ruby/test_env.rb	(revision 63188)
@@ -281,6 +281,17 @@ class TestEnv < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ruby/test_env.rb#L281
     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)
Index: hash.c
===================================================================
--- hash.c	(revision 63187)
+++ hash.c	(revision 63188)
@@ -4068,6 +4068,35 @@ env_keep_if(VALUE ehash) https://github.com/ruby/ruby/blob/trunk/hash.c#L4068
 }
 
 /*
+ *  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) https://github.com/ruby/ruby/blob/trunk/hash.c#L4778
     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);

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]