Skip to content
Permalink
Browse files
Fix Kernel#rand when given a Float exclusive range.
  • Loading branch information
jemc committed Jan 23, 2016
1 parent 9da9d6a commit fa397f821d96bfe2384ae9c4aa6a53b76c4993d0
Showing with 68 additions and 4 deletions.
  1. +2 −2 kernel/common/random.rb
  2. +66 −2 spec/ruby/core/kernel/rand_spec.rb
@@ -66,9 +66,9 @@ def random_integer(limit)
end

def random_range(limit)
min, max = limit.max.coerce(limit.min)
min, max = limit.last.coerce(limit.first)
diff = max - min
diff += 1 if max.kind_of?(Integer)
diff += 1 if max.kind_of?(Integer) && !limit.exclude_end?
random(diff) + min
end

@@ -49,8 +49,72 @@
rand l
end

it "returns a float for an range argument where max is < 1" do
rand(0.25..0.75).should be_kind_of(Float)
context "given an exclusive range" do
it "returns an Integer between the two Integers" do
1000.times do
x = rand(4...6)
x.should be_kind_of(Integer)
(4...6).should include(x)
end
end

it "returns a Float between the given Integer and Float" do
1000.times do
x = rand(4...6.5)
x.should be_kind_of(Float)
(4...6.5).should include(x)
end
end

it "returns a Float between the given Float and Integer" do
1000.times do
x = rand(3.5...6)
x.should be_kind_of(Float)
(3.5...6).should include(x)
end
end

it "returns a Float between the two given Floats" do
1000.times do
x = rand(3.5...6.5)
x.should be_kind_of(Float)
(3.5...6.5).should include(x)
end
end
end

context "given an inclusive range" do
it "returns an Integer between the two Integers" do
1000.times do
x = rand(4..6)
x.should be_kind_of(Integer)
(4..6).should include(x)
end
end

it "returns a Float between the given Integer and Float" do
1000.times do
x = rand(4..6.5)
x.should be_kind_of(Float)
(4..6.5).should include(x)
end
end

it "returns a Float between the given Float and Integer" do
1000.times do
x = rand(3.5..6)
x.should be_kind_of(Float)
(3.5..6).should include(x)
end
end

it "returns a Float between the two given Floats" do
1000.times do
x = rand(3.5..6.5)
x.should be_kind_of(Float)
(3.5..6.5).should include(x)
end
end
end
end

0 comments on commit fa397f8

Please sign in to comment.