简体   繁体   English

Ruby在1行代码中读/写文件

[英]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. 我是Ruby的新手,我正在研究一些katas,我坚持这个愚蠢的问题。 I need to copy the content of 1 file to a new file in 1 line of code 我需要将1个文件的内容复制到1行代码中的新文件中

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 Ruby 1.9.3及更高版本有一个

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. name是文件的名称, string是你想要写的,其他参数在我头上。

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). 一些链接: https//github.com/ruby/ruby/blob/ruby_1_9_3/NEWS,http//bugs.ruby-lang.org/issues/1081 (滚动到底部)。

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')) }

您可以执行以下操作:

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: 检查ruby文档:

IO::binwrite & IO::binread IO :: binwriteIO :: binread

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM