From: "David A. Black" Date: 2005-10-08T10:39:59+09:00 Subject: Re: Code for title-casing (US) snail addresses? Hi -- On Sat, 8 Oct 2005, rpardee@gmail.com wrote: > Far out--I'm going to have to ponder that one--learn what inject() > does. > > For now, here's what I've settled on: > > @abbreviations = %w(PO NE NW SE SW P.O. N.E. N.W. S.E. S.W. C/O P.O) > @suffixes = %w(ST ND RD TH) > @prefixes = %w(Mc O' D') > @dash_reg = Regexp.new("([-/\"][A-Za-z])") > > def prettify(address) > ret = Array.new > address.split(' ').each do |word| > word.capitalize! unless (@abbreviations.include?(word) or > word[0..0] =~ /[0-9#]/ ) > word[2..2] = word[2..2].upcase if @prefixes.include?(word[0..1]) > word[-2, 2] = word[-2, 2].downcase if > @suffixes.include?(word[-2,2]) > ret << word > end > ret = ret.join(' ') > # puts ret > if ret =~ @dash_reg then ret.gsub(@dash_reg, $1.upcase) else ret end > end > > This seems to handle both apartment numbers, and hyphenated street > names: > > prettify("1234 SLEATER-KINNEY RD #A5") Just a few suggestions to prettify prettify :-) At the end, you don't need an 'if' clause; you can just do the gsub operation, and if there's no match, nothing will happen: ret.gsub(@dash_reg) { $1.upcase } Actually, you don't need ret at all. split returns an array, so all you have to do is join that array and filter it through the gsub. So the whole method could be: def prettify(address) address.split(' ').each do |word| word.capitalize! unless (@abbreviations.include?(word) or word[0..0] =~ /[0-9#]/ ) word[2..2] = word[2..2].upcase if @prefixes.include?(word[0..1]) word[-2, 2] = word[-2, 2].downcase if @suffixes.include?(word[-2,2]) end.join(' ').gsub(@dash_reg) { $1.upcase } end David -- David A. Black dblack@wobblini.net