TitleCase
John Gruber posted his title case script the other day which prompted a request from Dan Benjamin to convert it into Ruby. This is my quick and dirty attempt.
If only I was such a highly skilled regexp ninja as Gruber is!.
#!/usr/bin/env ruby -wKU
class TitleCase
@small_words = %w(a an and as at but by en for if in of on or the to v[.]? via vs[.]?);
@small_words_r = /(#{@small_words.join("|")})\b/
@inline_period = /[[:alpha:]|[:digit:]][.][[:alpha:]|[:digit:]]/
@special_case = /AT&T|Q&A/i
@uppercase_word = /[[:upper:]]{2,}/
# Static/Class method to do the work
def TitleCase.parse(str)
result = []
# split on white space
str.each("\s") do |word|
word.strip!
# do not downcase SEC etc.
if @uppercase_word.match(word) then result << word; next end
word.downcase!
# capitalise all but small_words_r and inline_period
word.capitalize! unless @small_words_r.match(word) || @inline_period.match(word)
# deal with special cases
word.upcase! if @special_case.match(word)
result << word
end
# capitalize first and last word
result[0].capitalize! unless @inline_period.match(result[0])
result[result.size-1].capitalize! unless @inline_period.match(result[result.size-1])
result.join(" ")
end
end
# Test line
#puts TitleCase.parse("Does this work? a an this is daringfireball.net vs. hivelogic.com")
text = STDIN.gets
puts TitleCase.parse(text)
No Comments Yet