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 /mrbgems/mruby-enum-ext | |
| parent | 027d6407cc7c90324173799ade724aa6860206d0 (diff) | |
| download | mruby-5ac737cf88865a1b960ca2120f899069412bf085.tar.gz mruby-5ac737cf88865a1b960ca2120f899069412bf085.zip | |
add Enumerable#sort_by
Diffstat (limited to 'mrbgems/mruby-enum-ext')
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 21 |
1 files changed, 21 insertions, 0 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: |
