如果字符串中的每个单词(a)大写(即只有单词的第一个字母大写)或(b)被认为是一个例外并完全放入小写除非它是第一个单词,它总是大写。
我正在尝试编写一个函数,将字符串转换为标题大小写,给定一个可选的异常列表(次要单词)。次要单词列表将作为字符串给出,每个单词用空格分隔。我希望我的函数应该忽略次要单词字符串的大小写——即使次要单词字符串的大小写改变,它也应该以相同的方式运行。
例子:
title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
title_case('the quick brown fox') # should return: 'The Quick Brown Fox'
这是我迄今为止所尝试的,除其他外。
def title_case(title, minor_words = '')
minor_words = ["a", "an", "the", "of", "in", "and", "or", "nor", "like", "with", "by", "bc"]
title_bare = title.gsub(/\w+/) { |w| w = w.capitalize unless minor_words.include?(w); w }
if title_bare[0..0] =~ /[a-z]/
first_word = title_bare.split.first
return title_bare.sub(first_word, first_word.capitalize)
else
title_bare.to_s
end
end
提前致谢!