Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby capitalize every word first letter

Tags:

string

ruby

People also ask

How do you auto capitalize the first letter of every word?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.

How do you capitalize the first letter in Ruby?

Ruby | String capitalize() Method capitalize is a String class method in Ruby which is used to return a copy of the given string by converting its first character uppercase and the remaining to lowercase.

Do you capitalize the first letter of each word?

You should always capitalize the first letter of the first word in a sentence, no matter what the word is. Take, for example, the following sentences: The weather was beautiful. It was sunny all day. Even though the and it aren't proper nouns, they're capitalized here because they're the first words in their sentences.


In Rails:

"kirk douglas".titleize => "Kirk Douglas"
#this also works for 'kirk_douglas'

w/o Rails:

"kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")

#OBJECT IT OUT
def titleize(str)
  str.split(/ |\_/).map(&:capitalize).join(" ")
end

#OR MONKEY PATCH IT
class String  
  def titleize
    self.split(/ |\_/).map(&:capitalize).join(" ")
  end
end

w/o Rails (load rails's ActiveSupport to patch #titleize method to String)

require 'active_support/core_ext'
"kirk douglas".titleize #=> "Kirk Douglas"

(some) string use cases handled by #titleize

  • "kirk douglas"
  • "kirk_douglas"
  • "kirk-douglas"
  • "kirkDouglas"
  • "KirkDouglas"

#titleize gotchas

Rails's titleize will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:

"hEy lOok".titleize #=> "H Ey Lo Ok"

because it is meant to handle camel-cased code like:

"kirkDouglas".titleize #=> "Kirk Douglas"

To deal with this edge case you could clean your string with #downcase first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:

"kirkDouglas".downcase.titleize #=> "Kirkdouglas"

try this:

puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')

#=> One Two Three Four

or

puts 'one TWO three foUR'.split.map(&:capitalize)*' '

"hello world".titleize which should output "Hello World".


Another option is to use a regex and gsub, which takes a block:

'one TWO three foUR'.gsub(/\w+/, &:capitalize)

Look into the String#capitalize method.

http://www.ruby-doc.org/core-1.9.3/String.html#method-i-capitalize


"hello world".split.each{|i| i.capitalize!}.join(' ')

If you are trying to capitalize the first letter of each word in an array you can simply put this:

array_name.map(&:capitalize)