gpt4 book ai didi

ruby - 在 Ruby 1.8.7 中使用标题大小写

转载 作者:太空宇宙 更新时间:2023-11-03 16:06:18 26 4
gpt4 key购买 nike

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

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

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

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

为了找到解决方案,我可以采取哪些最有效的后续步骤?谢谢!

最佳答案

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

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"

关于ruby - 在 Ruby 1.8.7 中使用标题大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13117340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com