本文介绍了在 Ruby 1.8.7 中使用标题大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串中的某些字母大写以使其仅指定单词大写.

How can I capitalize certain letters in a string to make it so that only designated words are capitalized.

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

Must Past These Test:"barack obama" == "Barack Obama"&"the catcher in the rye" == "The Catcher in the Rye"

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

So far I have a method that will capitalize all words:

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

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

What are the most efficient next steps I could take to arrive at a solution? Thanks!

推荐答案

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

You could create a list of the word you don't want to capitalize and do

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.

By the way, if you were using Rails and did not need to exclude specific words you could use titleize.

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

这篇关于在 Ruby 1.8.7 中使用标题大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:27