Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby file IO delimiters?

I am trying to parse a text file that contains a variable number of words and numbers per line, like this:

foo 4.500 bar 3.00
1.3 3 foo bar

How can I read the file delimited by spaces instead of newlines? Is there some way I can set the File("file.txt").foreach method to use a spaces instead of newlines as a delimiter?

like image 658
jergason Avatar asked Feb 21 '10 07:02

jergason


2 Answers

You can use

open('file.txt').read.split.each

to give you an iterator over space (or newline) separated words.

like image 68
Peter Avatar answered Sep 21 '22 19:09

Peter


File.open("file.txt").read.split(" ").each

like image 38
Postnap Avatar answered Sep 22 '22 19:09

Postnap