Project

General

Profile

fetch_at.patch

wojtekmach (Wojtek Mach), 07/09/2014 06:52 PM

View differences:

hash.c
1202 1202
    return result;
1203 1203
}
1204 1204

  
1205
/*
1206
 * call-seq:
1207
 *   hsh.fetch_at(key, ...)                 -> array
1208
 *   hsh.fetch_at(key, ...) { |key| block } -> array
1209
 *
1210
 * Return an array containing the values associated with the given keys
1211
 * but also raises an <code>KeyError</code> when one of keys can't be found.
1212
 * Also see <code>Hash#values_at</code> and <code>Hash#fetch</code>.
1213
 *
1214
 *   h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
1215
 *
1216
 *   h.fetch_at("cow", "cat")                   #=> ["bovine", "feline"]
1217
 *   h.fetch_at("cow", "bird")                  # raises KeyError
1218
 *   h.fetch_at("cow", "bird") { |k| k.upcase } #=> ["bovine", "BIRD"]
1219
 */
1220

  
1221
VALUE
1222
rb_hash_fetch_at(int argc, VALUE *argv, VALUE hash)
1223
{
1224
    VALUE result = rb_ary_new2(argc);
1225
    long i;
1226

  
1227
    for (i=0; i<argc; i++) {
1228
      rb_ary_push(result, rb_hash_fetch(hash, argv[i]));
1229
    }
1230
    return result;
1231
}
1232

  
1205 1233
static int
1206 1234
select_i(VALUE key, VALUE value, VALUE result)
1207 1235
{
......
3816 3844
    rb_define_method(rb_cHash,"keys", rb_hash_keys, 0);
3817 3845
    rb_define_method(rb_cHash,"values", rb_hash_values, 0);
3818 3846
    rb_define_method(rb_cHash,"values_at", rb_hash_values_at, -1);
3847
    rb_define_method(rb_cHash,"fetch_at", rb_hash_fetch_at, -1);
3819 3848

  
3820 3849
    rb_define_method(rb_cHash,"shift", rb_hash_shift, 0);
3821 3850
    rb_define_method(rb_cHash,"delete", rb_hash_delete, 1);
test/ruby/test_hash.rb
499 499
    assert_equal ['three', nil, 'one', 'nil'], res
500 500
  end
501 501

  
502
  def test_fetch_at
503
    res = @h.fetch_at
504
    assert_equal(0, res.length)
505

  
506
    res = @h.fetch_at(3, 2, 1, nil)
507
    assert_equal(4, res.length)
508
    assert_equal %w( three two one nil ), res
509

  
510
    assert_raises KeyError do
511
      @h.fetch_at(3, 'invalid')
512
    end
513

  
514
    res = @h.fetch_at(3, 'invalid') { |k| k.upcase }
515
    assert_equal %w( three INVALID ), res
516
  end
502 517

  
503 518
  def test_invert
504 519
    h = @h.invert