开发者

Easy question: Read file, reverse it and write to another file in Ruby

I have:

 o = File.new("ouput.txt", "rw+")
 File.new("my_file.txt").lines.reverse_开发者_JAVA技巧each { |line|
       ?????  line 
 }
 o.close

I don't know what method to use to write to the file output o


puts understands arrays, so you can simplify this to:

File.open("f2.txt","w") {|o| o.puts File.readlines("f1.txt").reverse}


You're gonna wanna do something more like...

new_text = File.readlines('my_file').reverse.join
File.open('my_file', 'w+') { |file| file.write(new_text) }

Check out this documentation to figure out what w+ means.


I knew it was easy, what I don't quite get is why is not documented here?

o = File.new("ouput.txt", "w+")
File.new("my_file.txt").lines.reverse_each { |line|
    o.puts line 
}
o.close


For large files, avoid using readlines, as it'll be really slow/inefficient. Consider using a gem like Elif for this sort of thing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜