]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/commitdiff
Extend Numeric class with a clip() method to force a number to be in a given range
authorGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Fri, 6 Apr 2007 10:56:01 +0000 (10:56 +0000)
committerGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Fri, 6 Apr 2007 10:56:01 +0000 (10:56 +0000)
lib/rbot/core/utils/extends.rb

index 4b7e57f35da8675a4cdf2b4561ef11145ab29514..b812a6766f7f587a55f823f7bdbe3814ca301926 100644 (file)
@@ -27,6 +27,24 @@ class ::Array
   end
 end
 
+# Extensions for the Numeric classes
+#
+class ::Numeric
+
+  # This method forces a real number to be not more than a given positive
+  # number or not less than a given positive number, or between two any given
+  # numbers
+  #
+  def clip(left,right=0)
+    raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
+    l = [left,right].min
+    u = [left,right].max
+    return l if self < l
+    return u if self > u
+    return self
+  end
+end
+
 # Extensions to the String class
 #
 # TODO make ircify_html() accept an Hash of options, and make riphtml() just