Ruby:Titleize:如何忽略较小的单词,如“and"、“the"、“or"等 [英] Ruby: Titleize: How do I ignore smaller words like 'and', 'the', 'or, etc
问题描述
def titleize(string)
string.split(" ").map {|word| word.capitalize}.join(" ")
end
这会为每个单词加上标题,但我如何捕获某些我不想大写的单词?
This titleizes every single word, but how do I capture certain words I don't want capitalized?
即)杰克和吉尔
请不要使用正则表达式.
And please DO NOT USE Regex.
更新:
我在使这段代码工作时遇到问题:我让它打印了一个全部大写的单词数组,但不是没有下面的列表.
I am having trouble making this code work: I got it to print an array of words all caps, but not without the list below.
words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
def titleize(string)
cap_word = string.split(" ").map {|word| word.capitalize}
cap_word.include?(words_no_cap)
end
推荐答案
您可能想要为 Rails 提供的现有 titleize
函数.
You probably want to create an extension to the existing titleize
function that Rails provides.
为此,只需在初始化程序中包含以下文件,然后就可以了!即时提供异常,或者有选择地修改我的示例以将默认值添加到初始化程序中.
To do so, just include the following file in an initializer, and presto! Supply exceptions on the fly or optionally modify my example to add defaults into the initializer.
我知道您不想使用 Regex,但是,嘿,实际的 rails 函数使用 Regex,所以您最好保持同步.
I realize that you didn't want to use Regex, but hey, the actual rails function uses Regex so you might as well keep it in sync.
将此文件放在Rails.root/lib/string_extension.rb
中并加载到初始化程序中;或者只是把它扔进初始化程序本身.
Put this file in Rails.root/lib/string_extension.rb
and load it in an initializer; or just throw it in the initializer itself.
更新:由于@svoop 建议添加结束词边界,因此修改了 REGEX.
UPDATE: modified the REGEX on this thanks to @svoop's suggestion for adding the ending word boundary.
# encoding: utf-8
class String
def titleize(options = {})
exclusions = options[:exclude]
return ActiveSupport::Inflector.titleize(self) unless exclusions.present?
self.underscore.humanize.gsub(/\b(?<!['’`])(?!(#{exclusions.join('|')})\b)[a-z]/) { $&.capitalize }
end
end
这篇关于Ruby:Titleize:如何忽略较小的单词,如“and"、“the"、“or"等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!