ruby-changes:48115
From: glass <ko1@a...>
Date: Sat, 21 Oct 2017 15:08:39 +0900 (JST)
Subject: [ruby-changes:48115] glass:r60229 (trunk): hash.c: Add Hash#slice
glass 2017-10-21 15:08:33 +0900 (Sat, 21 Oct 2017) New Revision: 60229 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=60229 Log: hash.c: Add Hash#slice * hash.c (rb_hash_slice): add Hash#slice [Feature #8499] Modified files: trunk/hash.c trunk/test/ruby/test_hash.rb Index: hash.c =================================================================== --- hash.c (revision 60228) +++ hash.c (revision 60229) @@ -1325,6 +1325,38 @@ rb_hash_reject(VALUE hash) https://github.com/ruby/ruby/blob/trunk/hash.c#L1325 } /* + * 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) https://github.com/ruby/ruby/blob/trunk/hash.c#L4617 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); Index: test/ruby/test_hash.rb =================================================================== --- test/ruby/test_hash.rb (revision 60228) +++ test/ruby/test_hash.rb (revision 60229) @@ -1006,6 +1006,14 @@ class TestHash < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ruby/test_hash.rb#L1006 assert_equal(nil, h.select!{true}) end + def test_slice + h = @cls[1=>2,3=>4,5=>6] + assert_equal({1=>2, 3=>4}, h.slice(1, 3)) + assert_equal({}, h.slice(7)) + assert_equal({}, h.slice) + assert_equal({}, {}.slice) + end + def test_clear2 assert_equal({}, @cls[1=>2,3=>4,5=>6].clear) h = @cls[1=>2,3=>4,5=>6] -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/