"Joseph Paish" <jpaish / freenet.edmonton.ab.ca> schrieb im Newsbeitrag
news:04020607523103.01075 / localhost.localdomain...
> 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