Ruby:Titleize:如何忽略较小的单词,如'和','the','或等

问题描述 投票:8回答:9
def titleize(string)
  string.split(" ").map {|word| word.capitalize}.join(" ")
end

这标题化每一个单词,但我如何捕获某些我不想大写的单词呢?

即)杰克和吉尔

请不要使用正则表达式。

更新:

我无法使这段代码工作:我得到它打印所有大写的单词数组,但不是没有下面的列表。

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
ruby string
9个回答
7
投票

您可能想要创建Rails提供的existing titleize函数的扩展。

为此,只需在初始化程序中包含以下文件即可!动态提供异常或者可选地修改我的示例以将默认值添加到初始化程序中。

我意识到你不想使用Regex,但是嘿,实际的rails功能使用了Regex,所以你可以保持同步。

将此文件放在Rails.root/lib/string_extension.rb中并将其加载到初始化程序中;或者只是把它扔进初始化器本身。

更新:由于@ svoop建议添加结束词边界,修改了REGEX。

# 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

3
投票

这是我的小代码。你可以将它折射成几行。

def titleize(str)
    str.capitalize!  # capitalize the first word in case it is part of the no words array
    words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
    phrase = str.split(" ").map {|word| 
        if words_no_cap.include?(word) 
            word
        else
            word.capitalize
        end
    }.join(" ") # I replaced the "end" in "end.join(" ") with "}" because it wasn't working in Ruby 2.1.1
  phrase  # returns the phrase with all the excluded words
end

3
投票

如果将它转换为config / initializers到一个新文件中(你可以将它命名为string.rb),你可以将自定义函数调用到任何字符串。确保你重新启动,然后你就可以像下面的那样运行“anystring”.uncapitalize_puncs

这比试图更改标题化的默认代码更容易。所以现在,你可以调用@ something.title.titleize.uncapitalize_puncs

class String

    def uncapitalize_puncs
        puncs = ["and", "the", "to", "of", "by", "from", "or"]
        array = self.split(" ")
        array.map! do |x| 
            if puncs.include? x.downcase
                x.downcase
            else
                x
            end
        end
        return array.join(" ")
    end

end

3
投票

如果您不想大写和/或,请执行以下操作:

def titleize(string)
  nocaps = "and"
  string.split(" ").map { |word| nocaps.include?(word) ? word : word.capitalize }.join(" ")
end

1
投票

@codenamev的答案并不是很有效:

EXCLUSIONS = %w(a the and or to)
"and the answer is all good".titleize(exclude: EXCLUSIONS)
# => "And the Answer Is all Good"
                        ^^^

排除应匹配尾随字边界。这是一个改进版本:

# 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

"and the answer is all good".titleize(exclude: EXCLUSIONS)
# => "And the Answer Is All Good"
                        ^^^

1
投票

metodo capitalize para títulos

def capitalizar_titulo(string)
    words_not_to_capitalize = ["a","e","i","o","u","ao","aos", "as", "nos","nós","no","na","mas", "mes", "da", "de", "di", "do", "das", "dos"]
    s = string.split.each{|str| str.capitalize! unless words_not_to_capitalize.include? (str.downcase) }
    s[0].capitalize + " " + s[1..-1].join(" ")
  end

0
投票

这非常简单,只需在调用captalize时添加一个条件:

$nocaps = ['Jack', 'Jill']

def titleize(string)
  string.split(" ").map {|word| word.capitalize unless $nocaps.include?(word)}.join(" ")
end

全局变量是针对此示例设计的,它可能是您实际应用程序中的实例变量。


0
投票

有些标题可能需要考虑边缘情况(双关语)。

例如,标题开头或标点符号后面的小词通常应该大写(例如“纳尼亚传奇:狮子,女巫和魔衣橱”,两者都有)。

人们可能也希望/需要强制小写单词,以便像“Jack And Jill”这样的输入被渲染为“Jack and Jill”。

有时您可能还需要检测一个单词(通常是品牌名称)何时必须保留不寻常的大写字母,例如“iPod”,或缩写词,例如“NATO”,或域名,“example.com”。

为了妥善处理此类情况,titleize gem是您的朋友,或者至少应该提供完整解决方案的基础。


0
投票
titleize("the matrix or titanic")

def titleize(string)
  no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
  string.split(" ").map { |word| no_cap.include?(word) ? word : 
  word.capitalize }.join(" ")
end

结果:

"the Matrix or Titanic"
© www.soinside.com 2019 - 2024. All rights reserved.