0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.