Skip to content

Commit 25398cf

Browse files
committed
[GR-18163] Fix Array#sample for [] when called without n and a Random is given
PullRequest: truffleruby/3216
2 parents 4036807 + 011b850 commit 25398cf

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Bug fixes:
1818
* Fix `Hash#{to_s,inspect}` for keys whose `#inspect` return a frozen String (#2613, @eregon).
1919
* Fix `Array#pack` with `x*` to not output null characters (#2614, @bjfish).
2020
* Fix `Random#rand` not returning random floats when given float ranges (#2612, @bjfish).
21+
* Fix `Array#sample` for `[]` when called without `n` and a `Random` is given (#2612, @bjfish).
2122

2223
Compatibility:
2324

spec/ruby/core/array/sample_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,18 @@
1919
[].sample.should be_nil
2020
end
2121

22+
it "returns nil for an empty array when called without n and a Random is given" do
23+
[].sample(random: Random.new(42)).should be_nil
24+
end
25+
2226
it "returns a single value when not passed a count" do
2327
[4].sample.should equal(4)
2428
end
2529

30+
it "returns a single value when not passed a count and a Random is given" do
31+
[4].sample(random: Random.new(42)).should equal(4)
32+
end
33+
2634
it "returns an empty Array when passed zero" do
2735
[4].sample(0).should == []
2836
end

src/main/ruby/truffleruby/core/array.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1049,7 +1049,10 @@ def sample(count=undefined, options=undefined)
10491049
rng = Kernel
10501050
end
10511051

1052-
return at rng.rand(size) unless count
1052+
size = self.size
1053+
unless count
1054+
return at(size < 2 ? 0 : rng.rand(size))
1055+
end
10531056

10541057
count = size if count > size
10551058

0 commit comments

Comments
 (0)