ruby-on-railsruby

Ruby on Rails Titleize Underscore,Hyphenated and Single Quote Name


Rails titleize method removes hyphen and underscore, and capitalize method does not capitalize the word comes after hyphen and underscore. I wanted to do something like following:

sam-joe denis-moore      → Sam-Joe Denis-Moore
sam-louise o'donnell     → Sam-Louise O'Donnell
arthur_campbell john-foo → Arthur_Campbell John-Foo"

What is pattern that need to use on gsub below for this:

"sam-joe denis-moore".humanize.gsub(??) { $1.capitalize }
# => "Sam-Joe Denis-Moore"

Any help is really appreciated


Solution

  • Try this:

    my_string.split(/([ _-])/).map(&:capitalize).join
    

    You can put whatever delimiters you like in the regex. I used , _, and -. So, for example:

    'sam-joe denis-moore'.split(/([ _-])/).map(&:capitalize).join
    

    Results in:

    'Sam-Joe Denis-Moore'
    

    What it does is:

    1. .split(/([ _-])/) splits the string into an array of substrings at the given delimiters, and keeps the delimiters as substrings
    2. .map(&:capitalize) maps the resulting array of strings to a new array of strings, capitalizing each string in the array (delimiters, when capitalized, are unaffected)
    3. .join joins the resulting array of substrings back together for the final result

    You could, if you want, monkey patch the String class with your own titleize:

    class String
      def my_titleize
        self.split(/([ _-])/).map(&:capitalize).join
      end
    end
    

    Then you can do:

    'sam-joe denis-moore'.my_titleize
    => 'Sam-Joe Denis-Moore'