Climate
Climate

Reputation: 3

Reading a specific column of data from a text file in Ruby

I have tried Googling, but I can only find solutions for other languages and the ones about Ruby are for CSV files.

I have a text file which looks like this

0.222222 0.333333 0.4444444 this is the first line.

There are many lines in the same format. All of the numbers are floats.

I want to be able to read just the third column of data (0.444444, the values under that) and ignore the rest of the data.How can I accomplish this?

Upvotes: 0

Views: 1412

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

You can still use CSV; just set the column separator to the space character:

require 'csv'

CSV.open('data', :col_sep=>" ").each do |row|
  puts row[2].to_f
end

You don't need CSV, however, and if the whitespace separating fields is inconsistent, this is easiest:

File.readlines('data').each do |line|
  puts line.split[2].to_f
end

I'd recommend breaking the task down mentally to:

  1. How can I read the lines of a file?
  2. How can I split a string around whitespace?

Those are two problems that are easy to learn how to handle.

Upvotes: 1

Related Questions