views:

114

answers:

4

The post office actually publishes a list of commonly used street suffixes in addresses:

http://www.usps.com/ncsc/lookups/abbr_suffix.txt

I want to take this list and make a ruby function that takes a string, takes the last word ("183 main strt".split[' '].last) and if it matches any of the commonly used street suffixes ("strt"), replace it with the official Postal Service Standard Suffix ("st").

Is there a better way to approach this than a massive str.sub.sub.sub.sub.sub?

A: 

You can make an array with all these common used sufixes, iterate them with the each method and process them in your string?

That surely would be more elegant than all those many subs.

Francisco Soto
+6  A: 

I would put the suffixes in a hash, where the common suffix is the key and the official suffix is the value. Then you can look up the last word in the hash.

SUFFIXES = { "ALLEE" => "ALY", "ALLEY" => "ALY" }

addy = "183 main allee"
last = addy.split.last.upcase
addy = addy[0..-last.length-1] + SUFFIXES[last] if SUFFIXES[last]
puts addy
Yes. Do it this way!
glenn mcdonald
did some quick testing and this method is about 2.1x faster than the one below
go minimal
Yeah, due to avoiding Regexp.
Konstantin Haase
i would drop 'addy =', use << over +, and probably wouldn't have the if (since nil.to_s == ''), but this is by far the best answer here
Matt Briggs
@Matt Briggs thanks for the suggestion, but I can't seem to get it to work. addy[0..-last.length-1] << SUFFIXES[last] is resulting in a "can't convert nil into String" error when there is no matching suffix.
+1  A: 
STREET_SUFFIXES = { "ALLEE" => "ALY", "ALLEY" => "ALY" }

def fix_address(string)
  string.gsub(/[^s]+$/) { STREET_SUFFIXES[$1.upcase] || $1 }
end

puts fix_address("183 main allee")
Konstantin Haase
A: 

Is there a better way to approach this...?

Use CASS software. It will standardize and validate all the components of the address, not just the street suffix.

CASS vendors are listed at http://ribbs.usps.gov/files/vendors/CASSN01D.TXT

http://www.semaphorecorp.com is a cheap example.

joe snyder