How to capitalize first letter of each word in the string

23,901

Solution 1

you can just use the .titleize like this "i want to make the first letter of each work into a cap".titleize

you can learn more about titleize from the apidocks

titleize(word) public

Capitalizes all the words and replaces some characters in the string to create a nicer looking title. titleize is meant for creating pretty output. It is not used in the Rails internals.

titleize is also aliased as as titlecase.

Examples:

"man from the boondocks".titleize   # => "Man From The Boondocks"
"x-men: the last stand".titleize    # => "X Men: The Last Stand"
"TheManWithoutAPast".titleize       # => "The Man Without A Past"
"raiders_of_the_lost_ark".titleize  # => "Raiders Of The Lost Ark"

how this actuality works

# File activesupport/lib/active_support/inflector/methods.rb, line 115
def titleize(word)
  humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
end

To Actually keep in "-" in the works we can add a new method to the string class like this.

# ./lib/core_ext/string.rb
class String
  #"goyette-xyz-is wide road".titleize_with_dashes#=> "Goyette-xyz-is Wide Road"
  def titleize_with_dashes
    humanize.gsub(/\b('?[a-z])/) { $1.capitalize }
  end
end

Solution 2

You could implement proper method by yourself:

class String
  def my_titleize
    split.map(&:capitalize).join(' ')
  end
end

"goyette-xyz-is wide road".my_titleize
#=> "Goyette-xyz-is Wide Road"

Solution 3

And if like for me right now you need to capitalize the first letter even for dashed words, you can do it like this:

def titleize_and_keep_dashes(text)
  text.split.map(&:capitalize).join(' ').split('-').map(&:titleize).join('-')
end
titleize_and_keep_dashes("goyette-xyz-is wide road")
# => "Goyette-Xyz Is Wide Road".
Share:
23,901
kashif
Author by

kashif

Updated on September 16, 2020

Comments

  • kashif
    kashif over 3 years

    How to capitalize first letter of each world in the string in Ruby on Rails:

    "goyette-xyz-is wide road".titleize returns "Goyette Xyz Is Wide Road".
    

    I want the output like:

    "goyette-xyz is wide road".SOME-FUNCTION should return "Goyette-xyz-is Wide Road".
    

    titleize removes the underscore and hyphens but i want to keep it in the string.