PaperMate
PaperMate

Reputation: 11

How to split line read from text file

I'm trying to read in each line of a text file where each line is formatted like this:

Bob,Daniels,40,50,60,70,80

I want to split the contents of each line based on commas but for some reason it's not working when I do this:

f = File.open("textfile.txt", "r")
f.each_line do |line|
  line.split(",")
end

What am I doing wrong here or is there a better way I could be doing this?

Upvotes: 1

Views: 4108

Answers (3)

Jim U
Jim U

Reputation: 3366

Outputs last name field from comma-delimited-file:

Program

f.each_line do |line|
  fields = line.split(",")
  puts fields[1]
end

Input (textfile.txt)

Bob,Daniels,40,50,60,70,80
John,Smith,40,50,60,70,80

Output

Daniels
Smith

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160631

You're reading a CSV ("comma-separated-value") file, so use the existing CSV class. CSV files have a lot of special-case situations that a naive split won't handle.

The documentation has a number of different examples for how to read or write from/to files or strings.

For example, from the documentation for reading a line at a time from a file:

CSV.foreach("path/to/file.csv") do |row|
  # use row here...
end

In your code the problem is:

f.each_line do |line|
  line.split(",")
end

each_line iterates over the file being read using an each block.

line.split(",")

splits the value but doesn't do anything with it, so the result is thrown away. You could assign the result to a variable or iterate over the resulting array:

foo = line.split(",")
# do something with foo

or:

line.split(",").each do |i|
  # do something with i
end

But again, the CSV specification is not simple so think twice before relying on split. For example, the following line is valid CSV:

this,"is,some,CSV",data

and should be parsed as:

["this", "is,some,CSV", "data"]

but split(",") will wrongly generate:

["this", "\"is", "some", "CSV\"", "data"]

and, because it's wrong, there'll be a lot of extra cleanup needed.

split will seem safe on a simple set of comma-separated values, leading you to think it's safe for everything until you run into the above type of situation.

Upvotes: 1

Alex Kojin
Alex Kojin

Reputation: 5214

You should save result of splitting, as example save it to variable:

result = []
f = File.open("textfile.txt", "r")
f.each_line {|line| result << line.split(",") }

Upvotes: 2

Related Questions