现在我有
value = "United states of america"
words_to_ignore = ["the","of"]
new_string = value.split(' ').map {|w| w.capitalize }.join(' ')
我在这里要做的是除了of
这个词,我希望其余的大写。因此输出将为United States of America
。现在我不确定,怎么做到这一点。
答案 0 :(得分:6)
试试这个:
new_string = value.split(' ')
.each{|i| i.capitalize! if ! words_to_ignore.include? i }
.join(' ')
答案 1 :(得分:1)
也许尝试类似的事情:
value = "United state of america"
words_to_ignore = ["the","of"]
new_string = value.split(' ').map do |w|
unless words_to_ignore.include? w
w.capitalize
else
w
end
end
new_string[0].capitalize!
new_string = new_string.join(' ')
答案 2 :(得分:1)
我建议使用散列将大小写过程和异常存储在一个包中:
value = 'united states of america'
title_cases = Hash.new {|_,k| k.capitalize }.merge({'of' => 'of', 'off' => 'off'})
new_string = value.split(" ").map {|w| title_cases[w] }.join(' ') #=> "United States of America"
答案 3 :(得分:1)
value = "United state of america"
words_to_ignore = Hash[%w[the of].map{|w| [w, w]}]
new_string = value.gsub(/\w+/){|w| words_to_ignore[w] || w.capitalize}
答案 4 :(得分:0)
您可以使用这种方式强制始终使用相同的结果:
downcase_words = ["of", "the"]
your_string.split(' ').each{ |word| (downcase_words.include? word.downcase) ?
word.downcase! : word.capitalize! }.join(' ')
而your_string可能是:
'美国'
'美利坚合众国'
' uNitE a stAteS of aMerIca'
结果将永远是:"美利坚合众国"