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?
The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With