Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Titleize: How do I ignore smaller words like 'and', 'the', 'or, etc

Tags:

string

ruby

def titleize(string)
  string.split(" ").map {|word| word.capitalize}.join(" ")
end

This titleizes every single word, but how do I capture certain words I don't want capitalized?

ie) Jack and Jill

And please DO NOT USE Regex.

UPDATE:

I am having trouble making this code work: I got it to print an array of words all caps, but not without the list below.

words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]

def titleize(string)
cap_word = string.split(" ").map {|word| word.capitalize}

cap_word.include?(words_no_cap)

end
like image 582
user2103064 Avatar asked Feb 26 '13 00:02

user2103064


2 Answers

You probably want to create an extension to the existing titleize function that Rails provides.

To do so, just include the following file in an initializer, and presto! Supply exceptions on the fly or optionally modify my example to add defaults into the initializer.

I realize that you didn't want to use Regex, but hey, the actual rails function uses Regex so you might as well keep it in sync.

Put this file in Rails.root/lib/string_extension.rb and load it in an initializer; or just throw it in the initializer itself.

UPDATE: modified the REGEX on this thanks to @svoop's suggestion for adding the ending word boundary.

# encoding: utf-8
class String
  def titleize(options = {})
    exclusions = options[:exclude]

    return ActiveSupport::Inflector.titleize(self) unless exclusions.present?
    self.underscore.humanize.gsub(/\b(?<!['’`])(?!(#{exclusions.join('|')})\b)[a-z]/) { $&.capitalize }
  end
end
like image 147
codenamev Avatar answered Sep 18 '22 13:09

codenamev


Here is my little code. You can refractor it into a few lines.

def titleize(str)
    str.capitalize!  # capitalize the first word in case it is part of the no words array
    words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
    phrase = str.split(" ").map {|word| 
        if words_no_cap.include?(word) 
            word
        else
            word.capitalize
        end
    }.join(" ") # I replaced the "end" in "end.join(" ") with "}" because it wasn't working in Ruby 2.1.1
  phrase  # returns the phrase with all the excluded words
end
like image 25
hken27 Avatar answered Sep 21 '22 13:09

hken27