4

现在我有

value = "United states of america"
words_to_ignore = ["the","of"]
new_string = value.split(' ').map {|w| w.capitalize }.join(' ')

我在这里要做的是除了单词之外of,我希望其余的都大写。所以输出将是United States of America. 现在我不确定,究竟该怎么做。

4

5 回答 5

6

试试这个:

  new_string = value.split(' ')
    .each{|i| i.capitalize! if ! words_to_ignore.include? i }
    .join(' ')
于 2013-02-11T19:10:34.827 回答
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(' ')
于 2013-02-11T19:08:56.803 回答
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"
于 2013-02-11T19:14:04.213 回答
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}
于 2013-02-12T03:40:10.277 回答
0

您可以使用这种方式来强制始终获得相同的结果:

downcase_words = ["of", "the"]
your_string.split(' ').each{ |word| (downcase_words.include? word.downcase) ? 
                                     word.downcase! : word.capitalize! }.join(' ')

your_string 可能是:

“美利坚合众国”
“美利坚合众国” “美利坚合众国

结果将永远是:“美利坚合众国”

于 2016-10-06T14:04:41.723 回答