U:RDoc::AnyMethod[iI"sort_by:ETI"Enumerable#sort_by;TF:publico:RDoc::Markup::Document:@parts[o:RDoc::Markup::Paragraph; [I"DSorts enum using a set of keys generated by mapping the ;TI"3values in enum through the given block.;To:RDoc::Markup::BlankLine o;
; [I"JThe result is not guaranteed to be stable. When two keys are equal, ;TI">the order of the corresponding elements is unpredictable.;T@o;
; [I"=If no block is given, an enumerator is returned instead.;T@o:RDoc::Markup::Verbatim; [I"7%w{apple pear fig}.sort_by { |word| word.length }
;TI"0 #=> ["fig", "pear", "apple"]
;T:@format0o;
; [ I"EThe current implementation of sort_by
generates an ;TI"Harray of tuples containing the original collection element and the ;TI"Imapped value. This makes sort_by
fairly expensive when ;TI"the keysets are simple.;T@o;; [
I"require 'benchmark'
;TI"
;TI"*a = (1..100000).map { rand(100000) }
;TI"
;TI"Benchmark.bm(10) do |b|
;TI"& b.report("Sort") { a.sort }
;TI"3 b.report("Sort by") { a.sort_by { |a| a } }
;TI" end
;T;
0o;
; [I"produces:;T@o;; [I",user system total real
;TI"=Sort 0.180000 0.000000 0.180000 ( 0.175469)
;TI"=Sort by 1.980000 0.040000 2.020000 ( 2.013586)
;T;
0o;
; [I"JHowever, consider the case where comparing the keys is a non-trivial ;TI"Ioperation. The following code sorts some files on modification time ;TI".using the basic sort
method.;T@o;; [I"files = Dir["*"]
;TI"Lsorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime }
;TI"2sorted #=> ["mon", "tues", "wed", "thurs"]
;T;
0o;
; [ I"FThis sort is inefficient: it generates two new File
;TI"Hobjects during every comparison. A slightly better technique is to ;TI"Juse the Kernel#test
method to generate the modification ;TI"times directly.;T@o;; [
I"files = Dir["*"]
;TI""sorted = files.sort { |a, b|
;TI"# test(?M, a) <=> test(?M, b)
;TI"}
;TI"2sorted #=> ["mon", "tues", "wed", "thurs"]
;T;
0o;
; [I"HThis still generates many unnecessary Time
objects. A ;TI"Fmore efficient technique is to cache the sort keys (modification ;TI"Etimes in this case) before the sort. Perl users often call this ;TI"Aapproach a Schwartzian transform, after Randal Schwartz. We ;TI"Aconstruct a temporary array, where each element is an array ;TI"Jcontaining our sort key along with the filename. We sort this array, ;TI"3and then extract the filename from the result.;T@o;; [ I"%sorted = Dir["*"].collect { |f|
;TI" [test(?M, f), f]
;TI"!}.sort.collect { |f| f[1] }
;TI"2sorted #=> ["mon", "tues", "wed", "thurs"]
;T;
0o;
; [I"?This is exactly what sort_by
does internally.;T@o;; [I"3sorted = Dir["*"].sort_by { |f| test(?M, f) }
;TI"1sorted #=> ["mon", "tues", "wed", "thurs"];T;
0:
@fileI"enum.c;T:0@omit_headings_from_table_of_contents_below0I"]enum.sort_by { |obj| block } -> array
enum.sort_by -> an_enumerator
;T0[ I"();T@`FI"Enumerable;TcRDoc::NormalModule00