Over a million developers have joined DZone.

Sortable Arrays Of Symbols In Ruby

DZone's Guide to

Sortable Arrays Of Symbols In Ruby

Free Resource
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

This lets me do things like the following:

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}