Reputation: 1147
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.
Upvotes: 18
Views: 25696
Reputation: 10111
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
Upvotes: 47
Reputation: 1376
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".
Upvotes: 2
Reputation: 6460
Add .capitalize
method to your String to get the First letter capitalized automatically.
Upvotes: -1
Reputation: 51171
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"
Upvotes: 6