Feature #10017 » fetch_at.patch
hash.c | ||
---|---|---|
return result;
|
||
}
|
||
/*
|
||
* call-seq:
|
||
* hsh.fetch_at(key, ...) -> array
|
||
* hsh.fetch_at(key, ...) { |key| block } -> array
|
||
*
|
||
* Return an array containing the values associated with the given keys
|
||
* but also raises an <code>KeyError</code> when one of keys can't be found.
|
||
* Also see <code>Hash#values_at</code> and <code>Hash#fetch</code>.
|
||
*
|
||
* h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
|
||
*
|
||
* h.fetch_at("cow", "cat") #=> ["bovine", "feline"]
|
||
* h.fetch_at("cow", "bird") # raises KeyError
|
||
* h.fetch_at("cow", "bird") { |k| k.upcase } #=> ["bovine", "BIRD"]
|
||
*/
|
||
VALUE
|
||
rb_hash_fetch_at(int argc, VALUE *argv, VALUE hash)
|
||
{
|
||
VALUE result = rb_ary_new2(argc);
|
||
long i;
|
||
for (i=0; i<argc; i++) {
|
||
rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
|
||
}
|
||
return result;
|
||
}
|
||
static int
|
||
select_i(VALUE key, VALUE value, VALUE result)
|
||
{
|
||
... | ... | |
rb_define_method(rb_cHash,"keys", rb_hash_keys, 0);
|
||
rb_define_method(rb_cHash,"values", rb_hash_values, 0);
|
||
rb_define_method(rb_cHash,"values_at", rb_hash_values_at, -1);
|
||
rb_define_method(rb_cHash,"fetch_at", rb_hash_fetch_at, -1);
|
||
rb_define_method(rb_cHash,"shift", rb_hash_shift, 0);
|
||
rb_define_method(rb_cHash,"delete", rb_hash_delete, 1);
|
test/ruby/test_hash.rb | ||
---|---|---|
assert_equal ['three', nil, 'one', 'nil'], res
|
||
end
|
||
def test_fetch_at
|
||
res = @h.fetch_at
|
||
assert_equal(0, res.length)
|
||
res = @h.fetch_at(3, 2, 1, nil)
|
||
assert_equal(4, res.length)
|
||
assert_equal %w( three two one nil ), res
|
||
assert_raises KeyError do
|
||
@h.fetch_at(3, 'invalid')
|
||
end
|
||
res = @h.fetch_at(3, 'invalid') { |k| k.upcase }
|
||
assert_equal %w( three INVALID ), res
|
||
end
|
||
def test_invert
|
||
h = @h.invert
|
- « Previous
- 1
- 2
- Next »