prepend file line number to array

J

Joseph Paish

using ruby, i am trying to read a file of a couple hundred lines into an
array and prepend (if there is such a word) the line number (starting at 1)
to the beginning of each line.

a simple example from the file follows :
01/02/2004 bought 100 widgets 19.95 company_1
01/02/2004 sold 5 widgets 22.95 company_2
01/02/2004 bought 50 widgets 19.95 company_1

what i would like to end up with is :

1 01/02/2004 bought 100 widgets 19.95 company_1
2 01/02/2004 sold 5 widgets 22.95 company_2
3 01/02/2004 bought 50 widgets 19.95 company_1


is there an array method that i can use on each element to prepend the line
number after reading the file into an array using IO.readlines?

thanks

joe
 
K

Kent S.

How about

ary = []
file.each_line {|line| ary << "#{file.lineno} #{line}" }

/kent
 
R

Robert Klemme

Joseph Paish said:
using ruby, i am trying to read a file of a couple hundred lines into an
array and prepend (if there is such a word) the line number (starting at 1)
to the beginning of each line.

a simple example from the file follows :
01/02/2004 bought 100 widgets 19.95 company_1
01/02/2004 sold 5 widgets 22.95 company_2
01/02/2004 bought 50 widgets 19.95 company_1

what i would like to end up with is :

1 01/02/2004 bought 100 widgets 19.95 company_1
2 01/02/2004 sold 5 widgets 22.95 company_2
3 01/02/2004 bought 50 widgets 19.95 company_1


is there an array method that i can use on each element to prepend the line
number after reading the file into an array using IO.readlines?

Either use "cat -n" or insert the number during writing of each line -
this is more efficient:

while ( line = ARGF.gets )
printf "%5d %s", ARGF.lineno, line
end

If you need to keep the lines in the array something like this might do

arr.each_with_index do |line, index|
print index, " ", line, "\n"
end

Regards

robert
 
G

Gavin Sinclair

what i would like to end up with is :
1 01/02/2004 bought 100 widgets 19.95 company_1
2 01/02/2004 sold 5 widgets 22.95 company_2
3 01/02/2004 bought 50 widgets 19.95 company_1

is there an array method that i can use on each element to prepend the line
number after reading the file into an array using IO.readlines?


Sure there is!

require 'extensions/all' # extensions.rubyforge.org
lines = lines.map_with_index { |line, i| "#{i+1} #{line}" }

Although this may be more efficient:

require 'extensions/all'
File.open(path) do |f|
lines = f.map_with_index { |line, i| "#{i+1} #{line}" }
end

Cheers,
Gavin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top