Project

General

Profile

Feature #8811 ยป rb_ary_has_index.patch

Simple implementation with test - phluid61 (Matthew Kerwin), 08/27/2013 09:04 AM

View differences:

array.c
1490 1490
    return Qnil;
1491 1491
}
1492 1492

  
1493
/*
1494
 *  call-seq:
1495
 *     ary.has_index?(idx)    -> true or false
1496
 *     ary.index?(idx)        -> true or false
1497
 *
1498
 *  Returns <code>true</code> if the given index is present in <i>ary</i>.
1499
 *
1500
 *     a = [ "a", "b", "c" ]
1501
 *     h.has_index?(0)    #=> true
1502
 *     h.has_index?(2)    #=> true
1503
 *     h.has_index?(3)    #=> false
1504
 *     h.has_index?(-1)   #=> true
1505
 *     h.has_index?(-4)   #=> false
1506
 *
1507
 */
1508

  
1509
static VALUE
1510
rb_ary_has_index(VALUE ary, VALUE pos)
1511
{
1512
    VALUE val;
1513
    long idx;
1514

  
1515
    idx = NUM2LONG(pos);
1516

  
1517
    if (idx < 0) {
1518
       idx += RARRAY_LEN(ary);
1519
    }
1520
    if (idx < 0 || RARRAY_LEN(ary) <= idx) {
1521
       return Qfalse;
1522
    }
1523
    return Qtrue;
1524
}
1525

  
1493 1526
VALUE
1494 1527
rb_ary_to_ary(VALUE obj)
1495 1528
{
......
5596 5629
    rb_define_method(rb_cArray, "clear", rb_ary_clear, 0);
5597 5630
    rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);
5598 5631
    rb_define_method(rb_cArray, "include?", rb_ary_includes, 1);
5632
    rb_define_method(rb_cArray, "has_index?", rb_ary_has_index, 1);
5633
    rb_define_method(rb_cArray, "index?", rb_ary_has_index, 1);
5599 5634
    rb_define_method(rb_cArray, "<=>", rb_ary_cmp, 1);
5600 5635

  
5601 5636
    rb_define_method(rb_cArray, "slice", rb_ary_aref, -1);
test/ruby/test_array.rb
932 932
    assert_equal(1, a.index(99) {|x| x == 'cat' })
933 933
  end
934 934

  
935
  def test_has_index
936
    a = @cls[ 'cat', 99, /a/, 99, @cls[ 1, 2, 3] ]
937
    assert(  a.has_index?(0))
938
    assert(  a.has_index?(4))
939
    assert(! a.has_index?(5))
940
    assert(  a.has_index?(-1))
941
    assert(  a.has_index?(-5))
942
    assert(! a.has_index?(-6))
943
  end
944

  
935 945
  def test_values_at
936 946
    a = @cls[*('a'..'j').to_a]
937 947
    assert_equal(@cls['a', 'c', 'e'], a.values_at(0, 2, 4))