help with parsing

M

Mayur Shivakumar

Hi ,
i am new to ruby and can anybody tell me way i can parse a tab
delimited text file and convert it into a hash. thank you.
 
S

Seebs

i am new to ruby and can anybody tell me way i can parse a tab
delimited text file and convert it into a hash. thank you.

It would depend on what was delimited by the tabs.

You might try:

x = File.read("data.text")
x.sub!(%r{.*\n}, '#')

This reads the contents of the file into a string, and turns it into
a hash (#).

-s
 
J

Jeremy Woertink

Mayur said:
Hi ,
i am new to ruby and can anybody tell me way i can parse a tab
delimited text file and convert it into a hash. thank you.

You can try

filename = "my_tab_delimeted_file.txt"

File.readlines(filename).each do |line|
line.split("\t").each do |item|
puts item
end
end


~Jeremy
 
M

Mayur Shivakumar

Jeremy said:
You can try

filename = "my_tab_delimeted_file.txt"

File.readlines(filename).each do |line|
line.split("\t").each do |item|
puts item
end
end


~Jeremy

Thanks ...but i want to convert to hash.and text file might look like
this

name score result
jermy 23 pass
anooj 1 fail
 
J

Justin Collins

Mayur said:
Hi ,
i am new to ruby and can anybody tell me way i can parse a tab
delimited text file and convert it into a hash. thank you.
Assuming you mean each line contains a key and a value separated by a
tab, you can do something like

results = Hash.new

File.open "your_file.txt" do |f|
f.each_line do |l|
key, value = l.chomp.split("\t")
results[key] = value
end
end

p results


-Justin
 
S

Seebs

Thanks ...but i want to convert to hash.and text file might look like
this
name score result
jermy 23 pass
anooj 1 fail

That's nice. What do you want the hash to look like?

What you show here is not the sort of thing a hash is usually much good at,
because a hash is key/value *pairs*, and you appear to have triplets.

-s
 

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
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top