1

有什么方法可以修改 Rails 附带的 titlecase 方法,使其将所有应该大写的东西大写,但从不采用任何已经大写的东西并将其变为小写?例如,标题“ABC 照片拍摄”应该变成“ABC 照片拍摄”而不是“ABC 照片拍摄”。

4

1 回答 1

1

据我所知,Rails 中没有这样的内置方法。我只是构建一个自定义的。

class String
  def smart_capitalize
    ws = self.split
    ws.each do |w|
      w.capitalize! unless w.match(/[A-Z]/)
    end
    ws.join(' ')    
  end
end

"ABC photo".smart_capitalize 
#=> "ABC Photo"

"iPad is made by Apple but not IBM".smart_capitalize
#=> "iPad Is Made By Apple But Not IBM"

添加:根据美联社风格排除不重要的词

class String
  def smart_capitalize
    ex = %w{a an and at but by for in nor of on or so the to up yet}
    ws = self.split
    ws.each do |w|
      unless w.match(/[A-Z]/) || ex.include?(w)
        w.capitalize! 
      end
    end
    ws.first.capitalize!
    ws.last.capitalize!
    ws.join(' ')    
  end
end

"a dog is not a cat".smart_capitalize
#=> "A Dog Is Not a Cat"

"Turn the iPad on".smart_capitalize
#=> "Turn the iPad On"
于 2013-07-08T03:50:06.323 回答