Converting upper-case string into title-case using Ruby

后端 未结 10 1406
小鲜肉
小鲜肉 2020-12-25 10:46

I\'m trying to convert an all-uppercase string in Ruby into a lower case one, but with each word\'s first character being upper case. Example:

convert \"MY STRING HE

10条回答
  •  梦谈多话
    2020-12-25 11:38

    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
    

    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.

提交回复
热议问题