将所有单词的首字母大写并保持已经资本化

时间:2015-07-23 00:59:31

标签: ruby-on-rails ruby string ruby-on-rails-4

使用rails 4,无法在此找到文档。我想将字符串中每个单词的第一个字母大写,但保留已经大写的字母。

我想要以下输出:

how far is McDonald's from here? => How Far Is McDonald's From Here?

MDMA is also known as molly => MDMA Is Also Known As Molly

i drive a BMW => I Drive A BMW

我认为.titleize会这样做,但这会将BMW变成Bmw。谢谢你的帮助。

3 个答案:

答案 0 :(得分:5)

您可以尝试以下操作:

a.split.map{|x| x.slice(0, 1).capitalize + x.slice(1..-1)}.join(' ')
# or
a.split.map{|x| x[0].upcase + x[1..-1]}.join(' ')
#=> ["MDMA Is Also Known As Molly",
     "How Far Is McDonald's From Here?",
     "I Drive A BMW"]

Demonstration

答案 1 :(得分:1)

您可以执行以下自定义方法:

string = "your string IS here"
output = []
string.split(' ').each do |word|
  if word =~ /[A-Z]/
    output << word
  else
    output << word.capitalize
  end
end
output.join(' ')

当然,这不会改变像“tEST”或“tEst”这样的词,因为它至少有一个大写字母。

答案 2 :(得分:0)

在保留现有大写字母的同时仅将首字母大写:

your_string.then { |s| s[0].upcase + s[1..-1] }