Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-13 of 13 total

Capitalizing titles with Ruby

This (mostly) follows the Microsoft Manual of Style for Technical Publications. Lame I know, but it's a reference:

class String
   def titlecase
      non_capitalized = %w{of etc and by the for on is at to but nor or a via}
      gsub(/\b[a-z]+/){ |w| non_capitalized.include?(w) ? w : w.capitalize  }.sub(/^[a-z]/){|l| l.upcase }.sub(/\b[a-z][^\s]*?$/){|l| l.capitalize }
   end
end


Examples:

"this is a story in the new york times".titleize # => "This is a Story In the New York Times"
"what in the world was that for?".titleize # => "What In the World Was That For?"
"searching for a CHEAP overhead projector?".titleize # => "Searching for a CHEAP Overhead Projector?"

String_Begins_With2

No more letter counting... :-)
edit: strncmp is faster...
function String_Begins_With($needle, $subject) {
 return (strncmp($subject, $needle, strlen($needle))==0);
}

String_Begins_With

No more letter counting... :-)
edit: see kirk's faster solution "String_Begins_With2"

function String_Begins_With($needle, $subject) {
 return (substr($subject, 0, strlen($needle))==$needle);
}
« Newer Snippets
Older Snippets »
Showing 11-13 of 13 total