sortable arrays of symbols in Ruby

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.

Ruby

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]

Cross-posted to my DZone Snippets page.

This entry was posted in Programming and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>