DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Capitalizing Titles In Ruby - Another Take...

08.05.2005
| 5113 views |
  • submit to reddit
        This code was inspired by Peter's code from May 17... 

I basically extended his idea to be more flexible and added ! methods to modify the string in place. I chose to use a different regex selector because using "\b" breaks on apostrophes and leave you with words like "You'Re" instead of "You're"...


class String

  def titlecase()
    ignore_list = %w{of etc and by the for on is at to but nor or a via}
    capitalize_all_ex(ignore_list)
  end

  def titlecase!()
    ignore_list = %w{of etc and by the for on is at to but nor or a via}
    capitalize_all_ex!(ignore_list)
  end

  def capitalize_all(force_downcase = true)
    ignore_list = %w{}
    capitalize_all_ex(ignore_list, force_downcase)
  end

  def capitalize_all!(force_downcase = true)
    ignore_list = %w{}
    capitalize_all_ex!(ignore_list, force_downcase)
  end

  def capitalize_all_ex(ignore_list, force_downcase = true)
    # if force_downcase is true then the 
    # string is, um, downcased first :-)
    if force_downcase
      self.downcase.gsub(/[\w\']+/){ |w| 
        ignore_list.include?(w) ? w : w.capitalize  
      }
    else
      self.gsub(/[\w\']+/){ |w| 
        ignore_list.include?(w) ? w : w.capitalize  
      }
    end
  end

  def capitalize_all_ex!(ignore_list, force_downcase = true)
    if force_downcase
      self.replace(self.downcase.gsub(/[\w\']+/){ |w| 
        ignore_list.include?(w) ? w : w.capitalize  
      })
    else
      self.replace(self.gsub(/[\w\']+/){ |w| 
        ignore_list.include?(w) ? w : w.capitalize  
      })
    end
  end
end