Project

General

Profile

Feature #16833 ยป add-enumerable-empty.patch

f3ndot (Justin Bull), 05/06/2020 02:30 PM

View differences:

enum.c
1067 1067
    }
1068 1068
}
1069 1069

  
1070
/*
1071
 *  call-seq:
1072
 *     enum.empty? -> true or false
1073
 *
1074
 *  Returns true if enumerable is empty?
1075
 *
1076
 *    [].to_enum.empty?        #=> true
1077
 *    [nil].to_enum.empty?     #=> false
1078
 *    [false].to_enum.empty?   #=> false
1079
 *    [1, 2, 3].to_enum.empty? #=> false
1080
 *
1081
 */
1082

  
1083

  
1084
static VALUE
1085
enum_empty(VALUE obj)
1086
{
1087
    long len = RARRAY_LEN(enum_to_a(0, 0, enum_take(obj, INT2FIX(1))));
1088
    return len == 0 ? Qtrue : Qfalse;
1089
}
1070 1090

  
1071 1091
/*
1072 1092
 *  call-seq:
......
4181 4201
    rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
4182 4202
    rb_define_method(rb_mEnumerable, "tally", enum_tally, 0);
4183 4203
    rb_define_method(rb_mEnumerable, "first", enum_first, -1);
4204
    rb_define_method(rb_mEnumerable, "empty?", enum_empty, 0);
4184 4205
    rb_define_method(rb_mEnumerable, "all?", enum_all, -1);
4185 4206
    rb_define_method(rb_mEnumerable, "any?", enum_any, -1);
4186 4207
    rb_define_method(rb_mEnumerable, "one?", enum_one, -1);
test/ruby/test_enum.rb
375 375
    assert_equal(true, {a: 1, b: 2}.any?(->(kv) { kv == [:b, 2] }))
376 376
  end
377 377

  
378
  def test_empty
379
    assert_equal(true, [].to_enum.empty?)
380
    assert_equal(true, @empty.empty?)
381
    assert_equal(false, @obj.empty?)
382
    assert_equal(false, [nil].to_enum.empty?)
383
    assert_equal(false, [0].to_enum.empty?)
384
    assert_equal(false, [false].to_enum.empty?)
385
    assert_equal(false, (1..Float::INFINITY).lazy.empty?)
386
  end
387

  
378 388
  def test_any_with_unused_block
379 389
    assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
380 390
      [1, 23].any?(1) {|x| x == 1 }