diff options
author | glass <glass@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2017-10-21 06:08:33 +0000 |
---|---|---|
committer | glass <glass@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2017-10-21 06:08:33 +0000 |
commit | 6c50bdda0b33f8031e54e3ea7857de43da821ead (patch) | |
tree | b9d944adb4640fdb92497cb65964e9b6fb46c6a9 | |
parent | d83f9745f5f4e3ed8cc0ce2b47c6dfbef498e42f (diff) | |
download | ruby-6c50bdda0b33f8031e54e3ea7857de43da821ead.tar.gz |
hash.c: Add Hash#slice
* hash.c (rb_hash_slice): add Hash#slice [Feature #8499]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60229 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r-- | hash.c | 33 | ||||
-rw-r--r-- | test/ruby/test_hash.rb | 8 |
2 files changed, 41 insertions, 0 deletions
@@ -1325,6 +1325,38 @@ rb_hash_reject(VALUE hash) } /* + * 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) 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); diff --git a/test/ruby/test_hash.rb b/test/ruby/test_hash.rb index ebc622a827..01b4f3a67d 100644 --- a/test/ruby/test_hash.rb +++ b/test/ruby/test_hash.rb @@ -1006,6 +1006,14 @@ class TestHash < Test::Unit::TestCase 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] |