Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a tab-separated line of text in Ruby?

I find Ruby's each function a bit confusing. If I have a line of text, an each loop will give me every space-delimited word rather than each individual character.

So what's the best way of retrieving sections of the string which are delimited by a tab character. At the moment I have:

line.split.each do |word|
...
end

but that is not quite correct.

like image 954
alamodey Avatar asked Mar 03 '09 10:03

alamodey


1 Answers

I'm not sure I quite understand your question, but if you want to split the lines on tab characters, you can specify that as an argument to split:

line.split("\t").each ...

or you can specify it as a regular expression:

line.split(/\t/).each ...

Each basically just iterates through all the items in an array, and split produces an array from a string.

like image 97
Ben Avatar answered Sep 20 '22 21:09

Ben