Archive for June, 2010

Title case for ruby strings

Tuesday, June 15th, 2010

Update: Turns out Rails has a :titleize method on all strings.

I don’t know why the code snippets out there for turning ruby strings into Title Case are so complicated. Here’s one I hacked out based off of Justin French’s string extensions.

It’s probably slower than the others, or missing some exceptions, but it’s good enough for my current purpose.

class String
  def titlecase
    downcase.split.map {|w| capitalization_exceptions.include?(w) ? w : w.capitalize}.join(" ").upfirst
  end
 
  def upfirst
    self[0,1].capitalize + self[1,length-1]
  end
 
  private
    def capitalization_exceptions
      [ 
        'of','a','the','and','an','or','nor','but','if','then','else','when','up','at','from','by','on',
        'off','for','in','out','over','to'
      ]
    end	
end

I love Ruby

Tuesday, June 8th, 2010
>> Dec[4] - 14.weeks
=> Sat, 28 Aug 2010