Parsing a file

Input file format (three columns, tabs delimited):
A \t X1, X2 \t Z1, Z2
B \t X3 \t Z3
C \t X4, X5, X6 \t Z4, Z5, Z6

Expected file format:
A X1 Z1
A X2 Z2
B X3 Z3
C X4 Z4
C X5 Z5
C X6 Z6

My code:
a = Array.new()
x = Array.new()
z = Array.new()
s = String.new()
open("c:\\temp\\a.txt").each {|e|
    a = e.split("\t")
    x = a[1].split(",")
    z = a[2].split(",")
    x.each_index {|i|
        s = a[0] +"\t" + x[i] +" \t" + z[i]
        puts s
    }
}

Can this be done in a more elegant manner?

···

--
Posted via http://www.ruby-forum.com/.

The approach is OK, these are mostly cosmetic touches:

  input = <<EOS
  A\tX1, X2\tZ1, Z2
  B\tX3\tZ3
  C\tX4, X5, X6\tZ4, Z5, Z6
  EOS

  input.each do |line|
    key, xs, zs = line.chomp.split("\t")
    xs = xs.split(/\s*,\s*/)
    zs = zs.split(/\s*,\s*/)
    xs.zip(zs) {|x, z| puts [key, x, z].join("\t")}
  end

···

On Thu, May 1, 2008 at 11:07 PM, Adam Masiarek <adam@masiarek.com> wrote:

Input file format (three columns, tabs delimited):
A \t X1, X2 \t Z1, Z2
B \t X3 \t Z3
C \t X4, X5, X6 \t Z4, Z5, Z6

Expected file format:
A X1 Z1
A X2 Z2
B X3 Z3
C X4 Z4
C X5 Z5
C X6 Z6

My code:
a = Array.new()
x = Array.new()
z = Array.new()
s = String.new()
open("c:\\temp\\a.txt").each {|e|
    a = e.split("\t")
    x = a[1].split(",")
    z = a[2].split(",")
    x.each_index {|i|
        s = a[0] +"\t" + x[i] +" \t" + z[i]
        puts s
    }
}

Can this be done in a more elegant manner?

IO.foreach("data"){|line|
  k, *vals = line.split( "\t" )
  vals.map{|x| x.split( "," )}.transpose.each{|x|
    puts [k, *x].join( "\t" ) }
}

···

On May 1, 4:07 pm, Adam Masiarek <a...@masiarek.com> wrote:

Input file format (three columns, tabs delimited):
A \t X1, X2 \t Z1, Z2
B \t X3 \t Z3
C \t X4, X5, X6 \t Z4, Z5, Z6

Expected file format:
A X1 Z1
A X2 Z2
B X3 Z3
C X4 Z4
C X5 Z5
C X6 Z6

My code:
a = Array.new()
x = Array.new()
z = Array.new()
s = String.new()
open("c:\\temp\\a.txt").each {|e|
    a = e.split("\t")
    x = a[1].split(",")
    z = a[2].split(",")
    x.each_index {|i|
        s = a[0] +"\t" + x[i] +" \t" + z[i]
        puts s
    }

}

Can this be done in a more elegant manner?