Skip to content

Commit be95012

Browse files
authored
Merge pull request #8956 from headius/range_count_block
Handle argument or block passed to Range#count
2 parents 21c220e + f9732d9 commit be95012

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

core/src/main/java/org/jruby/RubyRange.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1214,16 +1214,25 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) {
12141214

12151215
@JRubyMethod
12161216
public IRubyObject count(ThreadContext context, Block block) {
1217-
if (isBeginless || isEndless) return asFloat(context, RubyFloat.INFINITY);
1217+
if (!block.isGiven()) {
1218+
if (isBeginless || isEndless) return asFloat(context, RubyFloat.INFINITY);
12181219

1219-
if (begin instanceof RubyInteger) {
1220-
IRubyObject size = size(context);
1221-
if (!size.isNil()) return size;
1220+
if (begin instanceof RubyInteger) {
1221+
IRubyObject size = size(context);
1222+
if (!size.isNil()) return size;
1223+
}
1224+
1225+
// fall back on Enumerable logic for other cases
12221226
}
12231227

12241228
return RubyEnumerable.count(context, this, block);
12251229
}
12261230

1231+
@JRubyMethod
1232+
public IRubyObject count(ThreadContext context, IRubyObject arg, Block block) {
1233+
return RubyEnumerable.count(context, this, arg, block);
1234+
}
1235+
12271236
@JRubyMethod
12281237
public IRubyObject minmax(ThreadContext context, Block block) {
12291238
if (block.isGiven()) return Helpers.invokeSuper(context, this, context.runtime.getRange(), "minmax", NULL_ARRAY, block);

spec/ruby/core/range/count_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,18 @@
99
(...nil).count.should == inf
1010
(..10.0).count.should == inf
1111
end
12+
13+
it "accepts an argument for comparison using ==" do
14+
(1..10).count(2).should == 1
15+
end
16+
17+
it "uses a block for comparison" do
18+
(1..10).count{|x| x%2==0 }.should == 5
19+
end
20+
21+
it "ignores the block when given an argument" do
22+
-> {
23+
(1..10).count(4){|x| x%2==0 }.should == 1
24+
}.should complain(/given block not used/)
25+
end
1226
end

0 commit comments

Comments
 (0)