diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-03-17 01:09:07 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-03-17 01:09:07 +0900 |
| commit | 5ac737cf88865a1b960ca2120f899069412bf085 (patch) | |
| tree | 0463d3bdb56bd42aac5188c8476ae7f673d8ea0c | |
| parent | 027d6407cc7c90324173799ade724aa6860206d0 (diff) | |
| download | mruby-5ac737cf88865a1b960ca2120f899069412bf085.tar.gz mruby-5ac737cf88865a1b960ca2120f899069412bf085.zip | |
add Enumerable#sort_by
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 21 | ||||
| -rw-r--r-- | mrblib/enum.rb | 2 |
2 files changed, 22 insertions, 1 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb index 85779ee59..90f321596 100644 --- a/mrbgems/mruby-enum-ext/mrblib/enum.rb +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -161,6 +161,27 @@ module Enumerable h end + ## + # call-seq: + # enum.sort_by { |obj| block } -> array + # + # Sorts <i>enum</i> using a set of keys generated by mapping the + # values in <i>enum</i> through the given block. + def sort_by(&block) + ary = [] + orig = [] + self.each_with_index{|e, i| + orig.push(e) + ary.push([block.call(e), i]) + } + if ary.size > 1 + __sort_sub__(ary, ::Array.new(ary.size), 0, 0, ary.size - 1) do |a,b| + a <=> b + end + end + ary.collect{|e,i| orig[i]} + end + NONE = Object.new ## # call-seq: diff --git a/mrblib/enum.rb b/mrblib/enum.rb index 30ccc8c19..ea032524e 100644 --- a/mrblib/enum.rb +++ b/mrblib/enum.rb @@ -390,7 +390,7 @@ module Enumerable def sort(&block) ary = [] self.each{|*val| ary.push(val.__svalue)} - unless ary.empty? + if ary.size > 1 __sort_sub__(ary, ::Array.new(ary.size), 0, 0, ary.size - 1, &block) end ary |
