如何在Ruby on Rails中将字符串中每个世界的第一个字母大写:
"goyette-xyz-is wide road".titleize returns "Goyette Xyz Is Wide Road".
我希望输出如下:
"goyette-xyz is wide road".SOME-FUNCTION should return "Goyette-xyz-is Wide Road".
titleize删除下划线和连字符,但我想将其保留在字符串中。
答案 0 :(得分:41)
您可以像.titleize
"i want to make the first letter of each work into a cap".titleize
您可以从apidocks
了解有关titleize的更多信息titleize(word)public
将所有单词大写并替换字符串中的某些字符以创建更好看的标题。 titleize用于创建漂亮的输出。它没有在Rails内部使用。
titleize也被称为titlecase。
示例:
"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"
这种现实如何运作
# File activesupport/lib/active_support/inflector/methods.rb, line 115
def titleize(word)
humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
end
要在作品中保留“ - ”,我们可以像这样在字符串类中添加一个新方法。
# ./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
答案 1 :(得分:6)
您可以自己实施适当的方法:
class String
def my_titleize
split.map(&:capitalize).join(' ')
end
end
"goyette-xyz-is wide road".my_titleize
#=> "Goyette-xyz-is Wide Road"
答案 2 :(得分:2)
如果现在和我一样,你需要将第一个字母大写为虚线,你可以这样做:
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".
答案 3 :(得分:0)
将.capitalize
方法添加到您的String中,以便自动将首字母大写。