Created
January 6, 2010 06:30
-
-
Save softcraft-development/270080 to your computer and use it in GitHub Desktop.
Constrain a value between two values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Numeric | |
def between( *values ) | |
low = values.min | |
high = values.max | |
[[low,self].max, high].min | |
end | |
end | |
require "test/unit" | |
require "shoulda" | |
class TestNumericExtensions < Test::Unit::TestCase | |
context "An integer" do | |
setup do | |
@target = 8 | |
end | |
should "give the same results if the low and high values come in a different order" do | |
assert_equal @target, @target.between(16, 4) | |
end | |
should "give the same results if there are three values, not two" do | |
assert_equal @target, @target.between(4, 16, 32 ) | |
end | |
context "greater than the lowest value" do | |
setup do | |
@low = 4 | |
end | |
context "and less than the highest value" do | |
setup do | |
@high = 16 | |
end | |
should "be between the two, and return itself" do | |
assert_equal(@target, @target.between( @low, @high )) | |
end | |
end | |
end | |
context "less than the lowest value" do | |
setup do | |
@low = 16 | |
end | |
context "and less than the highest value" do | |
setup do | |
@high = 32 | |
end | |
should "be less than all, and return the lowest" do | |
assert_equal @low, @target.between( @low, @high ) | |
end | |
end | |
end | |
context "greater than the lowest value" do | |
setup do | |
@low = 4 | |
end | |
context "and greater than the highest value" do | |
setup do | |
@high = 6 | |
end | |
should "be greater than all, and return the high" do | |
assert_equal @high, @target.between( @low, @high ) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment