开发者

how to sort file in 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_properti开发者_Python百科es}").sort
File.open("#{$base_properties}","w") do |file|
  new_array.each {|n| file.puts(n)}
end

Is there a better way to sort file?


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)


File.open("out.txt", "w") do |file|
  File.readlines("in.txt").sort.each do |line|
    file.write(line.chomp<<"\n")
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜