Simple text parsing

Hello Everyone,

What is the best way to get this input

test.txt

David | Hansson | Chicago
Obie | Fernandez | Jacksonville

to this output:

First Name: David
Last Name: Hansson
City: Chicago

First Name: Obie
Last Name: Fernandez
City: Jacksonville

???

This is what I’ve tried so far… I’m pretty far off I believe. Any
suggestions would help with learning the ins and outs of Ruby (or
programming in general)


test.rb

myArray = []
file = File.open(“test.txt”, ‘r+’)
file.each_line do |line|
x = line.scan(/\w+/).inspect
myArray = x
puts myArray
end

my output

$ ruby test.rb
[“David”, “Hansson”, “Chicago”]
[“Obie”, “Fernandez”, “Jacksonville”]

Thanks in Advance
Remington Splettstoesser

“Remington Splettstoesser” [email protected] wrote in message
news:[email protected]
Hello Everyone,

What is the best way to get this input

test.txt

David | Hansson | Chicago
Obie | Fernandez | Jacksonville

to this output:

First Name: David
Last Name: Hansson
City: Chicago

First Name: Obie
Last Name: Fernandez
City: Jacksonville

???

This is what I’ve tried so far… I’m pretty far off I believe. Any
suggestions would help with learning the ins and outs of Ruby (or
programming in general)


test.rb

myArray = []
file = File.open(“test.txt”, ‘r+’)
file.each_line do |line|
x = line.scan(/\w+/).inspect
myArray = x
puts myArray
end

my output

$ ruby test.rb
[“David”, “Hansson”, “Chicago”]
[“Obie”, “Fernandez”, “Jacksonville”]

Thanks in Advance
Remington Splettstoesser

A solution is to use printf as in the folloving code:

test1.rb

file = File.open(“test.txt”, ‘r+’)
file.each_line do |line|
myArray = line.scan(/\w+/)

myArray = line.split(/[\s|]+/) Alternative solution to scan

printf(“\nFirst Name: %-s\nLast Name : %-s\nCity : %-s\n”,
*myArray)
end

Hth gfb

Watch out, both of these solutions will fail for

John | O’Brian | New York

Thank You gfb!

Remington

At 2010-04-08 10:44AM, “Remington Splettstoesser” wrote:

to this output:

First Name: David
Last Name: Hansson
City: Chicago

First Name: Obie
Last Name: Fernandez
City: Jacksonville

Looks like you have a specific field separator, so might as well use it:

print_format = "First Name: %s\nLast Name: %s\nCity: %s\n\n"

File.foreach("test.txt") do |line|
  first, last, city = line.chomp.split(/ \| /)
  print print_format % [first, last, city]
end