Ruby 用 1 行代码读取/写入文件
我是 Ruby 的新手,我正在研究一些 katas,但我陷入了这个愚蠢的问题。我需要用 1 行代码将 1 个文件的内容复制到一个新文件
首先尝试:
File.open(out, 'w').write(File.open(in).read)
很好,但这是错误的我需要关闭文件:
File.open(out, 'w') { |outf| outf.write(File.open(in).read) }
然后当然关闭读取:
File.open(out, 'w') { |outf| File.open(in) { |inf| outf.write(outf.read)) } }
这是我想到的,但是对我来说,它看起来不像 1 行代码:(
有想法吗?
问候,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Ruby 1.9.3 及更高版本有一个
允许您直接写入文件的命令。
name
是文件名,string
是你要写的内容,其他参数都在我的头顶上。它的一些链接:https://github.com/ruby/ruby/blob/ruby_1_9_3/NEWS ,http://bugs.ruby-lang.org/issues/1081(滚动到底部)。
Ruby 1.9.3 and later has a
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:
But I guess you're looking for something like:
您可以执行以下操作:
You can do the following:
您可以尝试:
检查 ruby 文档:
IO::binwrite & IO::binread
You can try:
Check the ruby docs:
IO::binwrite & IO::binread