11
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
4

10 回答 10

9

您可能想要创建Rails 提供的现有功能的扩展。titleize

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

我意识到您不想使用 Regex,但是,实际的 rails 函数使用 Regex,因此您不妨保持同步。

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

更新:由于@svoop 建议添加结束词边界,因此修改了正则表达式。

# 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
于 2013-07-25T13:44:22.410 回答
3

If you throw this into config/initializers into a new file (you can name it anything like string.rb), you can call your custom functions to any string. Make sure you restart, and then you will be able to run below like ex) "anystring".uncapitalize_puncs

This is easier than messing around trying to change the default code of titleize. So now, you can just call @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
于 2014-07-20T05:43:12.807 回答
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
于 2013-10-29T06:08:31.847 回答
3

如果您不想大写 and 或 the,只需执行以下操作:

def titleize(string)
  nocaps = "and"
  string.split(" ").map { |word| nocaps.include?(word) ? word : word.capitalize }.join(" ")
end
于 2015-01-06T05:28:08.920 回答
2

The answer of @codenamev is not quite doing the job:

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

Exclusions should match trailing word boundaries. Here's an improved version:

# 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"
                        ^^^
于 2013-12-27T10:50:59.673 回答
2

metodo 大写 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
于 2016-12-05T12:29:31.777 回答
0

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

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

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

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

于 2013-02-26T00:09:12.947 回答
0

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

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

人们可能还希望/需要将小字强制小写,以便像“Jack and Jill”这样的输入被呈现为“Jack and Jill”。

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

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

于 2016-10-11T00:37:34.243 回答
0

我认为短语的第一个单词必须大写:

class String

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

end
于 2021-12-21T11:40:52.847 回答
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"
于 2018-01-03T15:23:31.213 回答