summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-compar-ext
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2017-10-17 11:18:54 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2017-10-17 11:19:12 +0900
commit4e365156d130e94a9c7937f498b438183efca954 (patch)
tree0f95e52e755227335c541d53c202b5c8c9842461 /mrbgems/mruby-compar-ext
parent061d804a5906118e505c7fc3ae5051733e1c825e (diff)
downloadmruby-4e365156d130e94a9c7937f498b438183efca954.tar.gz
mruby-4e365156d130e94a9c7937f498b438183efca954.zip
Add `Comparable#clamp`; CRuby2.4
Diffstat (limited to 'mrbgems/mruby-compar-ext')
-rw-r--r--mrbgems/mruby-compar-ext/mrbgem.rake5
-rw-r--r--mrbgems/mruby-compar-ext/mrblib/compar.rb31
2 files changed, 36 insertions, 0 deletions
diff --git a/mrbgems/mruby-compar-ext/mrbgem.rake b/mrbgems/mruby-compar-ext/mrbgem.rake
new file mode 100644
index 000000000..dcf584339
--- /dev/null
+++ b/mrbgems/mruby-compar-ext/mrbgem.rake
@@ -0,0 +1,5 @@
+MRuby::Gem::Specification.new('mruby-compar-ext') do |spec|
+ spec.license = 'MIT'
+ spec.author = 'mruby developers'
+ spec.summary = 'Enumerable module extension'
+end
diff --git a/mrbgems/mruby-compar-ext/mrblib/compar.rb b/mrbgems/mruby-compar-ext/mrblib/compar.rb
new file mode 100644
index 000000000..d66f816ef
--- /dev/null
+++ b/mrbgems/mruby-compar-ext/mrblib/compar.rb
@@ -0,0 +1,31 @@
+module Comparable
+ ##
+ # Returns <i>min</i> if <i>obj</i> <code><=></code> <i>min</i> is less
+ # than zero, <i>max</i> if <i>obj</i> <code><=></code> <i>max</i> is
+ # greater than zero and <i>obj</i> otherwise.
+ #
+ # 12.clamp(0, 100) #=> 12
+ # 523.clamp(0, 100) #=> 100
+ # -3.123.clamp(0, 100) #=> 0
+ #
+ # 'd'.clamp('a', 'f') #=> 'd'
+ # 'z'.clamp('a', 'f') #=> 'f'
+ #
+ def clamp(min, max)
+ if (min <=> max) > 0
+ raise ArgumentError, "min argument must be smaller than max argument"
+ end
+ c = self <=> min
+ if c == 0
+ return self
+ elsif c < 0
+ return min
+ end
+ c = self <=> max
+ if c > 0
+ return max
+ else
+ return self
+ end
+ end
+end