зеркало из https://github.com/github/ruby.git
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
This commit is contained in:
Родитель
d83f9745f5
Коммит
6c50bdda0b
33
hash.c
33
hash.c
|
@ -1324,6 +1324,38 @@ rb_hash_reject(VALUE hash)
|
|||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* 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);
|
||||
|
|
|
@ -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]
|
||||
|
|
Загрузка…
Ссылка в новой задаче