Ruby复制文件

时间:2016-10-12 01:44:16

标签: ruby

我正在学习Ruby从学习ruby的艰难之路网站(练习17)。 我正在尝试将文件复制到另一个文件中。 它不是复制,而是写#。 请帮忙

puts "Hi, enter the file you'd like to copy"
from_file = $stdin.gets.chomp

puts "What's the name of the file you'd like to have it overwritten"
to_file = $stdin.gets.chomp

puts "You want to copy #{from_file} into #{to_file}, right?"
$stdin.gets.chomp

puts "Contents of #{from_file}:"
first_file = open(from_file)
puts first_file.read

puts "Contents of #{to_file}:"
second_file = open(to_file)
puts second_file.read

puts "now overwriting"
first_file = open(second_file, 'w')
first_file.write(second_file)

puts "Contents of #{from_file}:"
first_file = open(from_file)
puts first_file.read

puts "Contents of #{to_file}:"
second_file = open(to_file)
puts second_file.read

1 个答案:

答案 0 :(得分:5)

您需要保持文件名文件句柄之间的差异。此外,代码是非惯用的Ruby。要读取文件,来自PHP的人可能会写:

first_file = open(from_file)
first_file_contents = first_file.read
first_file.close

second_file = open(to_file, 'w')
second_file.write(first_file_contents)
second_file.close

这是有效的Ruby,但不是非常Rubyish Ruby。在了解了块之后,这要好得多:

File.open(from_file) do |first_file|
  File.open(to_file, 'w') do |second_file|
    second_file.write(first_file.read)
  end
end

更好地了解库,您可能会发现这个快捷方式:

first_file_contents = File.read(from_file)
File.write(to_file, second_file_contents)

更多经验会给你这个:

require 'fileutils'
FileUtils.copy_file(from_file, to_file)
编辑:感谢Stefan发现了一个缺失的论点。