tags:

views:

56

answers:

3

This is my file content.

Receivables=Por cobrar
Payables=Cuentos por pagar 
ytdPurchases.label=Purchases YTD
validationError.maxValue=Value is too large, maximum value allowed is {0}

i want to sort this content in alphabetic order ... how may i do that ??

Update: This code will sort my file.

new_array = File.readlines("#{$base_properties}").sort
File.open("#{$base_properties}","w") do |file|
  new_array.each {|n| file.puts(n)}
end

Is there a better way to sort file?

A: 
File.open("out.txt", "w") do |file|
  File.readlines("in.txt").sort.each do |line|
    file.write(line.chomp<<"\n")
  end
end
tjp
can i sort file without using two files ?
krunal shah
sure: `a = File.readlines("in.txt").sort` creates array `a` containing the sorted lines. then you can do anything you want with the results.
AShelly
+3  A: 

Assuming your file is called "abc"

`sort abc -o abc`

Ruby shouldn't be used as a golden hammer. By using the command sort it will be much faster.

Ryan Bigg
`strace` suggests that it works, but is it actually guaranteed that `abc` won't be overwritten too early as it would be with `sort <abc >abc` ?
taw
@taw: If I was to design it, I would sort the file and then output it to the file, so no unintended overwriting would happen. I think the people who design these commands are smarter than I and have thought of this already.
Ryan Bigg
Your belief in sanity of Unix commands is charmingly naive. I've seen enough to distrust them all instinctively ;-)
taw
I'd like to think they got this one right ;) How hard could it be to stuff up sorting?
Ryan Bigg
+1  A: 

Obvious simplification:

new_array = File.readlines("#{$base_properties}").sort
File.open("#{$base_properties}","w") do |file|
  file.puts new_array
end

I'd just define a method like this, doing the opposite of File.read. It's highly reusable, and really should be part of the standard:

def File.write!(path, contents)
  File.open(path, "w"){|fh| fh.write contents}
end

And then sorting becomes:

File.write!($base_properties, File.readlines($base_properties).sort.join)
taw