且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Ruby 将大写字符串转换为标题大小写

更新时间:2022-11-08 21:51:09

在尝试提出我自己的方法(包含在下面以供参考)时,我意识到有一些非常讨厌的极端情况.***使用 Facets 中已经提供的方法,这是最棒的 Ruby 库 evar:

While trying to come up with my own method (included below for reference), I realized that there's some pretty nasty corner cases. Better just use the method already provided in Facets, the mostest awesomest Ruby library evar:

require 'facets/string/titlecase'

class String
  def titleize
    split(/(\W)/).map(&:capitalize).join
  end
end

require 'test/unit'
class TestStringTitlecaseAndTitleize < Test::Unit::TestCase
  def setup
    @str = "i just saw \"twilight: new moon\", and man!   it's crap."
    @res = "I Just Saw \"Twilight: New Moon\", And Man!   It's Crap."
  end
  def test_that_facets_string_titlecase_works
    assert_equal @res, @str.titlecase
  end
  def test_that_my_own_broken_string_titleize_works
    assert_equal @res, @str.titleize # FAIL
  end
end

如果您想要一些更符合典型写作风格指南的内容(即不将and"之类的单词大写),GitHub 上有几个titleize" gems.

If you want something that more closely complies to typical writing style guidelines (i.e. does not capitalize words like "and"), there are a couple of "titleize" gems on GitHub.