parsing a file

A

Adam Masiarek

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 +" \t" + z
puts s
}
}


Can this be done in a more elegant manner?
 
X

Xavier Noria

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 +" \t" + z
puts s
}
}


Can this be done in a more elegant manner?


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
 
W

William James

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 +" \t" + z
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" ) }
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top