mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Add Comparable#clamp; CRuby2.4
This commit is contained in:
@@ -14,6 +14,9 @@ MRuby::GemBox.new do |conf|
|
||||
# Use standard Struct class
|
||||
conf.gem :core => "mruby-struct"
|
||||
|
||||
# Use Comparable module extension
|
||||
conf.gem :core => "mruby-compar-ext"
|
||||
|
||||
# Use Enumerable module extension
|
||||
conf.gem :core => "mruby-enum-ext"
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user