Created
September 30, 2009 17:16
-
-
Save milkfarm/198249 to your computer and use it in GitHub Desktop.
Name parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://artofmission.com/articles/2009/5/31/parse-full-names-with-ruby | |
class Name < ActiveRecord::Base | |
def self.parse(name) | |
return false unless name.is_a?(String) | |
# First, split the name into an array | |
parts = name.split | |
# If any part is "and", then put together the two parts around it | |
# For example, "Mr. and Mrs." or "Mickey and Minnie" | |
parts.each_with_index do |part, i| | |
if ["and", "&"].include?(part) and i > 0 | |
p3 = parts.delete_at(i+1) | |
p2 = parts.at(i) | |
p1 = parts.delete_at(i-1) | |
parts[i-1] = [p1, p2, p3].join(" ") | |
end | |
end | |
# Build a hash of the remaining parts | |
{ | |
:suffix => (s = parts.pop unless parts.last !~ /(\w+\.|[IVXLM]+|[A-Z]+)$/), | |
:last_name => (l = parts.pop), | |
:prefix => (p = parts.shift unless parts[0] !~ /^\w+\./), | |
:first_name => (f = parts.shift), | |
:middle_name => (m = parts.join(" ")) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment