Converting upper-case string into title-case using Ruby

后端 未结 10 1381
小鲜肉
小鲜肉 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:33

    I've try to improve code... ready for critics and suggestions.

    class Book
        attr_accessor :title
        def title=(new_title)
        notcap=%w(and the a in of an)
        str=''
        new_title.gsub(/(\w|\s)\w+/) do |word|
            word.strip!
            if not notcap.include? word
                   word.capitalize! 
            end
           str += ' ' + word 
        end
        str.strip!
        str = str[0].upcase + str[1..-1]
        @title = str
       end
    end
    

提交回复
热议问题