在Ruby 1.8.7中使用标题大小写 [英] Using title case with Ruby 1.8.7

查看:115
本文介绍了在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中使用标题大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆