From: "David A. Black" Date: 2005-10-08T08:09:27+09:00 Subject: Re: Code for title-casing (US) snail addresses? Hi -- On Sat, 8 Oct 2005, rpardee@gmail.com wrote: > And thanks again! > > If I can beg your indulgence a bit further... I'm having trouble > elaborating this so it does the right thing for street names like > 'McGrath'. The simpler version is: > > def prettify(address) > abbreviations = %w(PO NE NW SE SW) > prefixes2 = %w(Mc O' D') > prefixes3 = %w(Mac) > address.gsub!(/(\d)([A-Z]+)/) { $1 + $2.downcase } > address.gsub(/[A-Z]+/) do |w| > # abbreviations.include?(w) ? w : w.capitalize > if abbreviations.include?(w) then > w > else > w.capitalize > end > end > end > > Which works admirably, except it gives back "Mcgrath", rather than > "McGrath". > > I *thought* I'd be able to tack a second Array.include? on there, like > so: > > def prettify(address) > abbreviations = %w(PO NE NW SE SW) > prefixes2 = %w(Mc O' D') > prefixes3 = %w(Mac) > address.gsub!(/(\d)([A-Z]+)/) { $1 + $2.downcase } > address.gsub(/[A-Z]+/) do |w| > # abbreviations.include?(w) ? w : w.capitalize > if abbreviations.include?(w) then > w > else > w.capitalize That whole if statement is a no-op: you don't actually change w, and you don't return anything. > end > if prefixes2.include?(w[0..1]) then > w[2..2] = w[2..2].upcase > end if's return nil on failure. So when this doesn't happen, the return value of the whole block will be nil, which will be interpolated as an empty string. > end > end > > But when I do that, calls like prettify("20 E MCGRAW ST") just return > "20" > > I've read over the gsub docs, but don't see why the above does not work > as expected. Anybody got a clue for me? See notes above, and also see if this helps: def prettify(address) abbreviations = %w(PO NE NW SE SW) prefixes2 = %w(Mc O' D') prefixes3 = %w(Mac) address.gsub!(/\d[A-Z]+/) {|w| w.downcase } address.gsub(/[A-Z]+/) do |w| w.capitalize! unless abbreviations.include?(w) w[2..2] = w[2..2].upcase if prefixes2.include?(w[0..1]) w end end (Note that last 'w', which ensures that w is the return value of the block.) I look forward to seeing how you'll handle people named de Forest who live in Delaware :-) David -- David A. Black dblack@wobblini.net