add Enumerable#sort_by

This commit is contained in:
Yukihiro "Matz" Matsumoto
2014-03-17 01:09:07 +09:00
parent 027d6407cc
commit 5ac737cf88
2 changed files with 22 additions and 1 deletions
+21
View File
@@ -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:
+1 -1
View File
@@ -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