Never been to DZone Snippets before?

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

Alphabetical sorter (See related posts)

// This function sorts an array of objects that include this code, alphabetically
// That's nothing new, except this sorts strings starting with a number correctly!

  # ---
  # Sorting
  # ---
def <=>(other)
    regex = /^[\d]+/
    if self.title =~ regex
      our_num = Regexp.last_match[0].to_i
      if other.title =~ regex
        other_num = Regexp.last_match[0].to_i
        return our_num <=> other_num
      end
    end
    self.title <=> other.title
  end

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts