5

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?

Jamison Dance
  • 19,896
  • 25
  • 97
  • 99

3 Answers3

4

The accepted answer will slurp the file, which can be a problem with large text files.

A better solution is IO.foreach. It is idiomatic and will stream the file char by char:

File.foreach(filename," ") {|string| puts string}

Sample file containing "this is an example" results with

"this"
"is"
"an"
"example"
Community
  • 1
  • 1
Mike S
  • 11,329
  • 6
  • 41
  • 76
3

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

Postnap
  • 31
  • 1
3

You can use

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

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

Peter
  • 127,331
  • 53
  • 180
  • 211