Ruby: sort an array of characters

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

+5
source share
3 answers

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

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

+16
source

If you want to work with older rubies, as if they were 1.9, you can simply define <=> on Symbol

class Symbol
  include Comparable

  def <=>(other)
    self.to_s <=> other.to_s
  end
end
+5
source

You can use stone backports:

require 'rubygems'
require 'backports/1.9.1/symbol/comparison'
[:a, :d, :c, :b].sort
# => [:a, :b, :c, :d]
+2
source

All Articles