Skip to content

Instantly share code, notes, and snippets.

@dogweather
Created March 18, 2015 21:51
Show Gist options
  • Save dogweather/a39e71e19cab2d330fd1 to your computer and use it in GitHub Desktop.
Save dogweather/a39e71e19cab2d330fd1 to your computer and use it in GitHub Desktop.
Demonstrating ruby string extensions
# -*- coding: utf-8 -*-
require 'digest/md5'
require 'set'
class String
ARTICLES = Set.new [
'a','an','and','by','for','in','is','of','not','on','or','over','the','to','under', 'with']
def starts_with str
return self[0...str.length] == str
end
def md5_sum
return Digest::MD5.hexdigest(self)
end
#
# A better titleize that creates a usable
# title according to English grammar rules.
#
def titleize
result = []
for word in self.downcase.split(/[[:space:]]/) # handle unicode
if result.empty? || (! ARTICLES.include? word)
word = word.capitalize
end
result << word
end
return result.join(' ')
end
#
# Replace my value with the titleized version.
#
def titleize!
replace titleize
end
#
# Enhance with typographic characters:
# Single quotes: ’
# Section sign: §
# Double quotes: “”
#
def add_typography
return self.gsub("'", "’").gsub(/\bSec\./, '§').gsub(/"([^"]+)"/, '“\1”')
end
#
# Take text with potential encoding problems and
# aggressively make it safe for UTF-8 import.
#
def utf8_safe
return self.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment