开发者

ruby - find and replace in a string for commonly used street suffix

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

http://www.usps.com/ncsc/lookups/abbr_suffix.t开发者_StackOverflow中文版xt

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?


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


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")


+1 for using a CASS Vendor--especially one that provides an API that will always give back standardized results for real addresses. Further, some services will actually return the address components split for you (such as the Street Suffix). Because it was just verified using USPS data and conventions, the suffix is already in the USPS-preferred form. Here's some sample code that hits just such as API:

https://github.com/smartystreets/LiveAddressSamples/blob/master/ruby/street_address.rb

This code calls the SmartyStreets LiveAddress API (notice the 'street_suffix' field). I'm a software engineer at SmartyStreets and can answer any further questions you might have.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜