Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort file in ruby

Tags:

file

sorting

ruby

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?

like image 624
krunal shah Avatar asked Jul 28 '10 22:07

krunal shah


People also ask

How does sort work in Ruby?

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.


2 Answers

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.

like image 55
Ryan Bigg Avatar answered Nov 15 '22 06:11

Ryan Bigg


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)
like image 44
taw Avatar answered Nov 15 '22 08:11

taw