Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize first letter of each word in the string

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.

like image 319
kashif Avatar asked Oct 03 '13 08:10

kashif


2 Answers

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
like image 64
MZaragoza Avatar answered Oct 07 '22 18:10

MZaragoza


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"
like image 30
Marek Lipka Avatar answered Oct 07 '22 18:10

Marek Lipka