Project

General

Profile

Feature #14559 ยป env_slice.patch

Benoit_Tigeot (Benoit Tigeot), 03/29/2018 04:01 PM

View differences:

hash.c
4067 4067
    return envtbl;
4068 4068
}
4069 4069

  
4070
/*
4071
 *  call-seq:
4072
 *     ENV.slice(*keys) -> a_hash
4073
 *
4074
 *  Returns a hash containing only the given keys from ENV and their values.
4075
 *
4076
 *     ENV.slice("TERM","HOME")  #=> {"TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
4077
 */
4078
static VALUE
4079
env_slice(int argc, VALUE *argv)
4080
{
4081
    int i;
4082
    VALUE key, value, result;
4083

  
4084
    if (argc == 0) {
4085
        return rb_hash_new();
4086
    }
4087
    result = rb_hash_new_with_size(argc);
4088

  
4089
    for (i = 0; i < argc; i++) {
4090
        key = argv[i];
4091
        value = rb_f_getenv(Qnil, key);
4092
        if (value != Qnil)
4093
            rb_hash_aset(result, key, value);
4094
    }
4095

  
4096
    return result;
4097
}
4098

  
4070 4099
/*
4071 4100
 * call-seq:
4072 4101
 *   ENV.clear
......
4749 4778
    rb_define_singleton_method(envtbl, "delete", env_delete_m, 1);
4750 4779
    rb_define_singleton_method(envtbl, "delete_if", env_delete_if, 0);
4751 4780
    rb_define_singleton_method(envtbl, "keep_if", env_keep_if, 0);
4781
    rb_define_singleton_method(envtbl, "slice", env_slice, -1);
4752 4782
    rb_define_singleton_method(envtbl, "clear", rb_env_clear, 0);
4753 4783
    rb_define_singleton_method(envtbl, "reject", env_reject, 0);
4754 4784
    rb_define_singleton_method(envtbl, "reject!", env_reject_bang, 0);
test/ruby/test_env.rb
281 281
    end
282 282
  end
283 283

  
284
  def test_slice
285
    ENV.clear
286
    ENV["foo"] = "bar"
287
    ENV["baz"] = "qux"
288
    ENV["bar"] = "rab"
289
    assert_equal({}, ENV.slice())
290
    assert_equal({}, ENV.slice(""))
291
    assert_equal({}, ENV.slice("unknown"))
292
    assert_equal({"foo"=>"bar", "baz"=>"qux"}, ENV.slice("foo", "baz"))
293
  end
294

  
284 295
  def test_clear
285 296
    ENV.clear
286 297
    assert_equal(0, ENV.size)