Capitalizing titles

前端 未结 2 625
刺人心
刺人心 2021-01-15 03:55

I\'m trying to write a method that will capitalize titles. It should capitalize not every word, but only the big words if you will. Sometimes, it has to capitalize every wor

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 04:31

    Building off of Josh Voigts comment:

    def titleize(name)
      lowercase_words = %w{a an the and but or for nor of}
      name.split.each_with_index.map{|x, index| lowercase_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
    end
    

    You might want make lowercase_words a constant and move it out of the function since they won't ever change.

提交回复
热议问题