Big Al Ruby Newbie
Big Al Ruby Newbie

Reputation: 834

Parse Tab Delimited Text from POST

I have a API that is sending me Tab delimited information in a field Value

I need to parse this into separate fields:

Post:

"\nuserName\tpassword\tfName\tlName\tuserPhone\tcompName\tcontName\taddr1\taddr2\tcity\tstate\tpostalCode\tcountry\tphone\tfax\temail\tbusnType\tDOTNumber\tMCNumber\ntest\tabc123\tTest\tName\t(555) 555-5555\t\t\t\t\t\t\t58638\tUS\t(555) 555-5555\t(555) 555-5555\t\tTest\t12345678\tMC000000\n"

What the fields should match:

  userName        password        fName   lName   userPhone       compName        contName        addr1   addr2   city    state   postalCode      country phone   fax     email   busnType        DOTNumber       MCNumber
  test    abc123  Test    Name    (555) 555-5555                                                  58638   US      (555) 555-5555  (555) 555-5555          Test    12345678        MC000000

Not sure if i have to write it to csv file then read it or if i can read as is. or how to go about it.

Upvotes: 1

Views: 299

Answers (1)

infused
infused

Reputation: 24337

The easiest way will be to use Ruby's CSV standard library:

require 'csv'

s = "\nuserName\tpassword\tfName\tlName\tuserPhone\tcompName\tcontName\taddr1\taddr2\tcity\tstate\tpostalCode\tcountry\tphone\tfax\temail\tbusnType\tDOTNumber\tMCNumber\ntest\tabc123\tTest\tName\t(555) 555-5555\t\t\t\t\t\t\t58638\tUS\t(555) 555-5555\t(555) 555-5555\t\tTest\t12345678\tMC000000\n"

csv = CSV.new(s, col_sep: "\t")
csv.each do |row|
  puts row.inspect
end

And the output is:

[]
["userName", "password", "fName", "lName", "userPhone", "compName", "contName", "addr1", "addr2", "city", "state", "postalCode", "country", "phone", "fax", "email", "busnType", "DOTNumber", "MCNumber"]
["test", "abc123", "Test", "Name", "(555) 555-5555", nil, nil, nil, nil, nil, nil, "58638", "US", "(555) 555-5555", "(555) 555-5555", nil, "Test", "12345678", "MC000000"]

Upvotes: 2

Related Questions