【问题标题】:Using title case with Ruby 1.8.7在 Ruby 1.8.7 中使用标题大小写
【发布时间】:2014-12-17 13:42:26
【问题描述】:

如何将字符串中的某些字母大写,以便仅将指定的单词大写。

必须通过这些测试: “巴拉克奥巴马”==“巴拉克奥巴马” & "麦田里的守望者" == "麦田里的守望者"

到目前为止,我有一个方法可以将所有单词大写:

#Capitalizes the first title of every word.
def capitalize(words)
     words.split(" ").map {|words| words.capitalize}.join(" ")
end

接下来我可以采取哪些最有效的步骤来达成解决方案?谢谢!

【问题讨论】:

  • 你所说的“只有指定的单词大写”是什么意思,什么是“指定的”单词?
  • 抱歉,我应该更清楚地使用“标题案例”这个词。标题大小写将对标题或名称重要的单词大写。就像英语语法一样。因此,我所说的指定词的意思是必须大写才能使标题起作用的词。

标签: ruby rspec title-case


【解决方案1】:

你可以创建一个你不想大写的单词列表

excluded_words = %w(the and in) #etc

def capitalize_all(sentence, excluded_words)
  sentence.gsub(/\w+/) do |word|
    excluded_words.include?(word) ? word : word.capitalize
  end
end

顺便说一句,如果您使用的是 Rails 并且不需要排除特定的单词,您可以使用 titleize

"the catcher in the rye".titleize
#=> "The Catcher In The Rye"

【讨论】:

  • 似乎是一个很好的解决方案@oldergod,在我弄清楚你使用的所有简写概念(即带有“?”的条件语句)之后,我肯定会使用它。我对编程很陌生,我想进一步探索是否有一种更简单的方法可以处理这个不带正则表达式的方法(还没有到达那里)。干杯!
  • a ? b : c 与 ruby​​ 中的 if a then b else c end 相同。它被称为三元运算符。
  • 嘿@oldergod,引用你的代码,如果我想把“the”这个词大写,如果它首先出现的话。目前排除方法不能做到这一点。
  • @bigthyme 您可以在函数第一行的句子后添加.capitalize。这将使句子的第一个单词大写。
  • 非常感谢您的帮助!真的很感激。这些书不像老神那样具有互动性。
【解决方案2】:

这是另一种解决方案。它不是那么漂亮,但它处理的首字母缩略词是你想要保留所有的大写字母和缩略词,你不想像我以前使用的缩略词那样被弄乱。除此之外,它还确保您的第一个和最后一个单词大写。

class String
  def titlecase
    lowerCaseWords = ["a", "aboard", "about", "above", "across", "after", "against", "along", "amid", "among", "an", "and", "around", "as", "at", "before", "behind", "below", "beneath", "beside", "besides", "between", "beyond", "but", "by", "concerning", "considering", "d", "despite", "down", "during", "em", "except", "excepting", "excluding", "following", "for", "from", "in", "inside", "into", "it", "ll", "m", "minus", "near", "nor", "of", "off", "on", "onto", "opposite", "or", "outside", "over", "past", "per", "plus", "re", "regarding", "round", "s", "save", "since", "t", "than", "the", "through", "to", "toward", "towards", "under", "underneath", "unlike", "until", "up", "upon", "ve", "versus", "via", "with", "within", "without", "yet"]
    titleWords = self.gsub( /\w+/ )
    titleWords.each_with_index do | titleWord, i |
      if i != 0 && i != titleWords.count - 1 && lowerCaseWords.include?( titleWord.downcase )
        titleWord
      else
        titleWord[ 0 ].upcase + titleWord[ 1, titleWord.length - 1 ]
      end
    end
  end
end

这里有一些如何使用它的例子

puts 'barack obama'.titlecase # => Barack Obama
puts 'the catcher in the rye'.titlecase # => The Catcher in the Rye
puts 'NASA would like to send a person to mars'.titlecase # => NASA Would Like to Send a Person to Mars
puts 'Wayne Gretzky said, "You miss 100% of the shots you don\'t take"'.titlecase # => Wayne Gretzky Said, "You Miss 100% of the Shots You Don't Take"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    相关资源
    最近更新 更多