Gruber-style Title Case in Ruby

Posted by Ben Jackson Wed, 21 May 2008 16:11:00 GMT

As requested by hivelogic:

module TitleCase
  SMALL_WORDS = %w(a an and as at but by en for if in of on or the to v[.]? via vs[.]?)

  def self.convert input
    # then capitalize 
    input.gsub!(/\b([a-z])([a-z\-_]+)/) { "#{$1.capitalize}#{$2}" }
    input.gsub!(/(\b)(#{SMALL_WORDS.join("|")})(\b)/i) { "#{$1}#{$2.downcase}#{$3}" }

    # If the first/last word in the title is a small word, then capitalize it:
    input.sub!(/^(#{SMALL_WORDS.join("|")})\b/i) { $1.capitalize }
    input.sub!(/\b(#{SMALL_WORDS.join("|")})$/i) { $1.capitalize }

    # "v." and "vs.":
    input.gsub!(/ V(s?). /i){ "v#{$1}." }

    # 'S (otherwise you get "the SEC'S decision")
    input.gsub!(/(['’])S\b/i){"#{$1}s"}

    # "AT&T" and "Q&A", which get tripped up by 
    # self-contained small words "at" and "a"
    input.gsub!(/\b(AT&T|Q&A)\b/i){ $1.upcase }    

    input
  end
end

# some brief tests
puts TitleCase.convert("The book is On the table")
puts TitleCase.convert("the book is on the table")

# and the edge cases
puts TitleCase.convert("at&t u-verse marks one-year anniversary of giving los angeles")
puts TitleCase.convert("the SEC'S decision")

# Thanks Louije for pointing this case out
puts TitleCase.convert("iTunes users now happy with iPhoto")

Let me know of any bugs in the comments. Enjoy.

Posted in ,  | Tags , ,  | 2 comments | 4 trackbacks

Comments

  1. Louije said about 10 hours later:

    Check this case:

    iTunes users now happy with iPhoto

    Your script capitalizes the eyes. Pretty, though.

  2. Louije said about 10 hours later:

    (Pretty code, I meant :)

Trackbacks

Use the following link to trackback from your own site:
http://www.unfitforprint.com/trackbacks?article_id=gruber-style-title-case-in-ruby&day=21&month=05&year=2008

  1. From Soma.
    Soma drug history.
    Soma review the retail church chris thron. Soma prescription medicine.
  2. From Free casino games online.
    No deposit online casino.
    No deposit online bonus casino. Casino royale online viewing movie. Online casino ratings. Online casino forums. Lasvegas online casino. Online casino. Best online slots www.casino-slot-machine.net.
  3. From Buy xanax online.
    Buy xanax online.
    Buy xanax. Buy xanax without prescription. Buy xanax without prescription in usa. Where to buy xanax online without a prescription. Buy cheap xanax without prescription.
  4. From Cialis best price buy online.
    Link buy cialis online.
    Buy cialis phentermine. Buy cialis. Cialis best price buy online. Buy cialis buy viagara.

Comments are disabled