Skip to content

Commit 011b850

Browse files
committed
Fix Array#sample for [] when called without n and a Random is given
1 parent 8f5d1fc commit 011b850

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
@@ -15,6 +15,7 @@ Bug fixes:
1515
* Fix a resource leak from allocators defined in C extensions (@aardvark179).
1616
* `SIGINT`/`Interrupt`/`Ctrl+C` now shows the backtrace and exits as signaled, like CRuby (@eregon).
1717
* Update patch feature finding to prefer the longest matching load path (#2605, @bjfish).
18+
* Fix `Array#sample` for `[]` when called without `n` and a `Random` is given (#2612, @bjfish).
1819

1920
Compatibility:
2021

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
@@ -1050,7 +1050,10 @@ def sample(count=undefined, options=undefined)
10501050
rng = Kernel
10511051
end
10521052

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

10551058
count = size if count > size
10561059

0 commit comments

Comments
 (0)