Skip to content

Commit

Permalink
Fix Kernel#rand when given a Float exclusive range.
Browse files Browse the repository at this point in the history
  • Loading branch information
jemc committed Jan 23, 2016
1 parent 9da9d6a commit fa397f8
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 4 deletions.
4 changes: 2 additions & 2 deletions kernel/common/random.rb
Expand Up @@ -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

Expand Down
68 changes: 66 additions & 2 deletions spec/ruby/core/kernel/rand_spec.rb
Expand Up @@ -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

Expand Down

0 comments on commit fa397f8

Please sign in to comment.