DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Sortable Arrays Of Symbols In Ruby

04.01.2009
| 6271 views |
  • submit to reddit
        I got this error in my Rails app because I was trying to sort an array of symbols:  undefined method `<=>' for :my_symbol:Symbol.  I defined the spaceship method for the Symbol class and included the Comparable module in order to have other comparison methods available for symbols.

class Symbol
  include Comparable

  def <=>(other)
    self.to_s <=> other.to_s
  end
end

This lets me do things like the following:

irb(main):007:0> [:c, :a, :d, :b, :e].sort
=> [:a, :b, :c, :d, :e]