Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: sort array of symbols

since symbols do not respond to the <=> method used by sort, does anyone have a technique to sorting an array of symbols? interested in seeing some other ideas.

like image 724
brewster Avatar asked Nov 09 '10 02:11

brewster


2 Answers

Well, symbols.sort_by {|sym| sym.to_s} works.

Also in 1.9 symbols do respond to <=>, so there you can just do symbols.sort.

like image 96
sepp2k Avatar answered Oct 04 '22 10:10

sepp2k


If you want to work on older rubies as though they were 1.9 you can just define <=> on Symbol

class Symbol
  include Comparable

  def <=>(other)
    self.to_s <=> other.to_s
  end
end
like image 43
mmrobins Avatar answered Oct 04 '22 08:10

mmrobins