Ruby: Extend String Class to Capitalize Every Single Word


/ Published in: Ruby
Save to your folder(s)

Don't forget to use require 'directory/name_of_class'


Copy this code and paste it in your HTML
  1. # This helper is opening up core Ruby String class
  2. # in order to add a new method to all Strings
  3.  
  4. class String
  5.  
  6. # Ruby has a capitalize method (used below) which capitalizes the
  7. # first letter of a string. But in order to capitalize the first
  8. # letter of EVERY word we have to write our own.
  9.  
  10. def titleize
  11. self.split(' ').collect {|word| word.capitalize}.join(" ")
  12. end
  13.  
  14. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.