On Aug 10, 11:19 pm, Ryan Davis <ryand-r... / zenspider.com> wrote:
> On Aug 10, 2007, at 13:54 , William James wrote:
>
>
>
> > On Aug 10, 1:29 pm, Frank Meyer <lolz.ll... / gmail.com> wrote:
> >> I've written a little ruby program which can sort logfiles with the
> >> following format:
>
> >> 4.text text text
> >> 1.text text text
> >> 2.text text text
> >> 10.text text text
> >> 2.text2 text2 text2
> > ...
> > File.open( ARGV.first, "r+" ){|file|
> >   array = file.readlines
> >   file.rewind
> >   file.truncate(0)
> >   file.puts array.sort_by{|s| s[/^\d+/].to_i }
> > }
>
> your version takes a lot of memory,

Wrong.

When the number of lines to sort is small,
it uses a small amount of memory.
When the number of lines to sort is medium,
it uses a medium amount of memory.
When the number of lines to sort is large,
it uses a large amount of memory.

>                        is slow,

Everything is relative.  If its speed is compared to the
speed of other versions written in scripting languages, it
is not slow.

>                                 and doesn't properly
> sort the content of the line,

Wrong.

Looking at the source code of the original poster immediately
reveals that he wants to sort only on the number at the
beginning of the line.


>                               just the number. swap the two "2."
> lines and you'll see what I mean. Using the right tool for the job
> (`sort`) does wonders:
>
> % ruby -e 'n = 1_000_000; File.open("blah.txt", "w") { |f| n.times
> { m = rand 5; f.puts "#{rand n}. file#{m} file#{m} file#{m}" } }'
> % cp blah.txt blah2.txt
> % time ruby -e 'File.open( ARGV.first, "r+" ) { |file| array =
> file.readlines; file.rewind; file.truncate(0); file.puts array.sort_by
> {|s| s[/^\d+/].to_i } }' blah.txt
> real    0m8.182s ...
> % time ruby -e 'path = ARGV.shift; system %(sort -n "#{path}" > "#
> {path}.tmp"); File.rename "#{path}.tmp", path' blah2.txt

Wrong.

The original poster stated:

> The file is given as a command line parameter and after sorting the
> entries it writes them back into this file.

Your code makes no attempt to write to the original file; it uses
a temporary file.

Furthermore, your solution won't even run:

E:\Ruby>ruby -e 'path = ARGV.shift; system %(sort -n "#{path}"
> "#{path}.tmp"); File.rename "#{path}.tmp", path' data
-e:1: unterminated string meets end of file

If your code is put in a file ...

E:\Ruby>ruby try.rb data
Input file specified two times.

... it still won't work.

Perhaps your attempt at a solution requires Unix, and you,
in your ignorance, or your thoughtlessness, or your
ignorance and your thoughtlessness, assumed that every
user of Ruby is a user of Unix.