diff --git a/mrbgems/default.gembox b/mrbgems/default.gembox index 64f05de10..65584681d 100644 --- a/mrbgems/default.gembox +++ b/mrbgems/default.gembox @@ -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" 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 min if obj <=> min is less + # than zero, max if obj <=> max is + # greater than zero and obj 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