From: Benedikt Heinen Date: 2005-11-17T21:15:20+09:00 Subject: Re: extracting lines from an address >> 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 } puts "A : '#{address}'" puts "A1: '#{al1}'" puts "A2: '#{al2}'" # yes - for this example, I'm not checking puts "A3: '#{al3}'" # whether I get LESS than the 4 lines I puts "A4: '#{al4}'" # wanted... if remains != [] puts "oops... there are more than just the expected 4 lines" remains.each do |r| puts " trailing line: #{r}" end end Running this will print: A : ' 12, HouseName Street City Country ' A1: '12, HouseName' A2: 'Street' A3: 'City' A4: 'Country' 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)