The simplest code for sorting arrays in ruby?

I usually do something like

array.sort{|a,b| a.something <=> b.something}

How can I do it?

+5
source share
4 answers

use sort_by

array.sort_by{|e| e.something}

or

sort_lambda = lambda{|e| e.something}
array.sort_by(&sort_lambda)

With the latter, you can reuse sort_lambda in other sort_by statements

+19
source

In Rails, or rather, with ActiveSupport or in Ruby 1.9 (maybe 1.8.7, not sure), you can use the new short sharpness:

array.sort_by(&:something)

, sort_by , , (, , : ): "-" , . .

+5

+1 Eimantas, , , , , , /a/. , <= > . :.

class Album
 def sort_value
    @sv ||= @name.downcase.sub(/^\W*(the|an|a) /,"")
  end

  def <=>(other)
    sort_value <=> (other.sort_value rescue other)
  end
end
+5

Comparable a b ?

0

All Articles