Project

General

Profile

Bug #15929 ยป array-minmax.patch

jeremyevans0 (Jeremy Evans), 06/17/2019 06:47 PM

View differences:

array.c
4846 4846
    return result;
4847 4847
}
4848 4848

  
4849
/*
4850
 *  call-seq:
4851
 *     ary.minmax                       -> [obj, obj]
4852
 *     ary.minmax {| a,b | block }      -> [obj, obj]
4853
 *
4854
 *  Returns a two element array which contains the minimum and the
4855
 *  maximum value in the array.
4856
 *
4857
 *  Can be given an optional block to override the default comparison
4858
 *  method <code>a <=> b</code>.
4859
 */
4860
static VALUE
4861
rb_ary_minmax(VALUE ary)
4862
{
4863
    if (rb_block_given_p()) {
4864
        return rb_call_super(0, NULL);
4865
    }
4866
    return rb_assoc_new(rb_ary_min(0, 0, ary), rb_ary_max(0, 0, ary));
4867
}
4868

  
4849 4869
static int
4850 4870
push_value(st_data_t key, st_data_t val, st_data_t ary)
4851 4871
{
......
6898 6918

  
6899 6919
    rb_define_method(rb_cArray, "max", rb_ary_max, -1);
6900 6920
    rb_define_method(rb_cArray, "min", rb_ary_min, -1);
6921
    rb_define_method(rb_cArray, "minmax", rb_ary_minmax, 0);
6901 6922

  
6902 6923
    rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
6903 6924
    rb_define_method(rb_cArray, "uniq!", rb_ary_uniq_bang, 0);
test/ruby/test_array.rb
1774 1774
    assert_same(obj, [obj, 1.0].max)
1775 1775
  end
1776 1776

  
1777
  def test_minmax
1778
    assert_equal([1, 3], [1, 2, 3, 1, 2].minmax)
1779
    assert_equal([3, 1], [1, 2, 3, 1, 2].minmax {|a,b| b <=> a })
1780
    cond = ->((a, ia), (b, ib)) { (b <=> a).nonzero? or ia <=> ib }
1781
    assert_equal([[3, 2], [1, 3]], [1, 2, 3, 1, 2].each_with_index.minmax(&cond))
1782
    ary = %w(albatross dog horse)
1783
    assert_equal(["albatross", "horse"], ary.minmax)
1784
    assert_equal(["dog", "albatross"], ary.minmax {|a,b| a.length <=> b.length })
1785
    assert_equal([1, 3], [3,2,1].minmax)
1786

  
1787
    class << (obj = Object.new)
1788
      def <=>(x) 1 <=> x end
1789
      def coerce(x) [x, 1] end
1790
    end
1791
    ary = [obj, 1.0].minmax
1792
    assert_same(obj, ary[0])
1793
    assert_equal(obj, ary[1])
1794
  end
1795

  
1777 1796
  def test_uniq
1778 1797
    a = []
1779 1798
    b = a.uniq