Reading specific columns on a text file

Hello everyone.

I’m working on script here and I need do read the 1st and the 10th
columns on a file like this

R357 10011G1 0 0.0 0 0 0.0 381654.8 7993255.6 827.9 1235959

As reference I used the code found in this post:
http://www.ruby-forum.com/topic/161462#new

The difference is on that snippet the user only wanted to read the first
column, so I tried something like this

file = File.open(" “)
columns = []
file.each_line do |line|
columns << line.split(” ")[0 , 11]
end

p columns

Aparently It reads every column from 0 to 11

line.split(" ")[0 , 11] does, in fact, return 11 items, starting from
0th.

To return 0th and 11th column, use line.split(" ").values_at(0, 11),

– Matma R.

On Feb 2, 2012, at 11:51 AM, Cassio Godinho wrote:

The difference is on that snippet the user only wanted to read the first
column, so I tried something like this

file = File.open(" “)
columns = []
file.each_line do |line|
columns << line.split(” ")[0 , 11]

“R357 10011G1 0 0.0 0 0 0.0 381654.8 7993255.6 827.9
1235959”.split(" ").values_at(0,10)
=> [“R357”, “1235959”]

(the 11th element is at index 10 when you start from 0)

Array#[] with [0,11] means start from the element at index 0 and take 11
elements.

-Rob

Bartosz Dziewoński wrote in post #1043736:

line.split(" ")[0 , 11] does, in fact, return 11 items, starting from
0th.

To return 0th and 11th column, use line.split(" ").values_at(0, 11),

– Matma R.

Thank you very much, that was perfect.
By the way, what are my options in case I want to use those values to
plot a chart using only ruby and gems? For web I could just use
Highcharts or anything like that, but im making a command line script,
if I could display a window with the graph it would be perfect.

On Thu, Feb 2, 2012 at 6:20 PM, Rob B.
[email protected] wrote:

As reference I used the code found in this post:
Read text file - Ruby - Ruby-Forum

The difference is on that snippet the user only wanted to read the first
column, so I tried something like this

file = File.open(" “)
columns = []
file.each_line do |line|
columns << line.split(” ")[0 , 11]

File opening and iteration can be done simpler:

File.foreach do |line|
a, b = line.split.values_at(0, 10)
end

“R357 10011G1 0 0.0 0 0 0.0 381654.8 7993255.6 827.9 1235959”.split("
").values_at(0,10)
=> [“R357”, “1235959”]

Minor nitpick: you do not even need the argument to #split because
splitting at whitespace is the default.

Kind regards

robert