开发者

Ruby read/write to file in 1 line of code

I am kind of a newbie to Ruby, I am working out some katas and I stuck on this silly problem. I need to copy the content of 1 file to a new file in 1 line of code

First try:

File.open(out, 'w').write(File.open(in).read)

Nice, but it's wrong I need to 开发者_运维百科close the files:

File.open(out, 'w') { |outf| outf.write(File.open(in).read) }

And then of course close the read:

File.open(out, 'w') { |outf| File.open(in) { |inf| outf.write(outf.read)) } }

This is what I come up with, but it does not look like 1 line of code to me :(

Ideas?

Regards,


Ruby 1.9.3 and later has a

File.write(name, string, [offset], open_args)

command that allows you to write a file directly. name is the name of the file, string is what you want to write, and the other arguments are above my head.

Some links for it: https://github.com/ruby/ruby/blob/ruby_1_9_3/NEWS , http://bugs.ruby-lang.org/issues/1081 (scroll to the bottom).


There are many ways. You could simply invoke the command line for example:

`cp path1 path2`

But I guess you're looking for something like:

File.open('foo.txt', 'w') { |f| f.write(File.read('bar.txt')) }


You can do the following:

File.open(out_file, "w") {|f| f.write IO.read(in_file)}


You can try:

IO.binwrite('to-filename', IO.binread('from-filename'))

Check the ruby docs:

IO::binwrite & IO::binread

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜