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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With