了解 Ruby 中的 IO 方法和对象



我正在按照 learnrubythehardway 学习 Ruby,在要求您解释某些事情的作用之前,它似乎非常简单明了。我已经在我的代码中评论了我认为程序中正在发生的事情。想看看我是否在目标上,需要重新思考事情或没有线索,应该停止尝试学习如何编码。

# Sets variables to arguments sent through terminal
from_file, to_file = ARGV
# Saves from_file object into in_file
in_file = open(from_file)
puts in_file
# Saves from_file data into indata
indata = in_file.read
puts indata
# Save to_file object into out_file with writing privileages
out_file = open(to_file, 'w')
puts out_file
# Writes(copies) indata into out_file
out_file.write(indata)
# Closes files so they can not be accessed anymore
out_file.close
in_file.close

终端中的输出如下所示:

#<File:0x0000000201b038>
This is text from the ex17_from.txt file.
Did it copy to the ex17_to.txt file?
#<File:0x0000000201ae58>

我们还被赋予了尝试减少所需代码量的任务,并被告知我们可以在一行代码中完成整个操作。我想我可以删除所有注释和 put 语句,而其他所有内容都放在一行代码中。但是,这将是一条很长的线,我认为这不是作者所要求的。关于如何缩短此代码的任何想法都会有所帮助。

我已经在我的代码中评论了我认为程序中正在发生的事情。想看看我是否在目标上,需要重新考虑事情或没有线索

你需要学会超越书面文字。例如,此评论毫无用处:

# Saves from_file object into in_file
in_file = open(from_file)

不仅没用,而且实际上是不正确的。这个from_file对象是什么?in_file会是什么样的对象?你为什么不以任何方式提及open

这里实际发生的是通过调用 open 创建 File/IO 对象。而from_file ,在这种情况下,是文件的路径。不是一个"对象",是吗?但in_file是一个完整的 File 对象,您可以使用它来读取文件的内容。

您的其他评论也是如此。您只需用人类的文字重写代码行,而无需描述代码背后的意图

您可以使用 FileUtils#cp 并执行以下操作:

require "fileutils"
FileUtils.cp *ARGV

*ARGV数组分成cp方法所需的两个参数


或者,下面是代码的简明版本:

# Sets variables to arguments sent through terminal
from_file, to_file = ARGV
# Saves from_file object into to_file
open(to_file, 'w') do |out|
  open(from_file) do |f|
      f.each do |line|
        out << line
      end
  end
end