From: William James Date: 2005-11-18T07:02:21+09:00 Subject: Re: extracting lines from an address Benedikt Heinen wrote: > >> I have an address stored in mysql as a text field. > >> I'm using ActiveRecord to access the field. > >> But how do I get each line of the address in to their own strings? > > >> Address = "12, HouseName > >> Street > >> City > >> Country" > >> > >> Address_line1 = "12, HouseName" > >> Address_line2 = "Street" > >> Address_line3 = "City" > >> Address_line4 = "Country" > > > > address = "12, HouseName > > Street > > City > > Country" > > > > address_lines = address.split( /\n\s*/ ) > > > > puts address_lines[0] > > > > address_line1, address_line2, address_line3, address_line4 = > > address.split( /\n\s*/ ) > > > > puts address_line4 > > > This method has a couple of minor shortcomings - it does not eliminate all > unnecessary whitespace (specifically, it does not look at whitespace at > the beginning of the address field - if there were any, nor does it look > at trailing whitespace). > > In that case, may I suggest the following solution? > (for readability, I have shortened Address_line1-4 to al1-4... > > > address = " 12, HouseName > Street > City > Country " > > # btw. you should never assume you'll just receive the 4 lines > # you were expecting - this is why I added in the *remains which > # will receive the extra lines, if any. > al1,al2,al3,al4,*remains =address.split("\n").map { |l| l.strip } I can't help but commend your work. However, it has the minor shortcoming that the split is not needed: al1,al2,al3,al4,*remains =address.map { |l| l.strip } > Benedikt > > ALLIANCE, n. In international politics, the union of two thieves who > have their hands so deeply inserted in each other's pockets that > they cannot separately plunder a third. > (Ambrose Bierce, The Devil's Dictionary) -- Commendation, n. The tribute we pay to achievements that resemble, but do not equal, our own. --- Ambrose Bierce