diff --git a/kernel/common/random.rb b/kernel/common/random.rb index 832c9d5dd0..0414ae1f67 100644 --- a/kernel/common/random.rb +++ b/kernel/common/random.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 diff --git a/spec/ruby/core/kernel/rand_spec.rb b/spec/ruby/core/kernel/rand_spec.rb index 554f11b4b1..95c03ebeaf 100644 --- a/spec/ruby/core/kernel/rand_spec.rb +++ b/spec/ruby/core/kernel/rand_spec.rb @@ -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