我正在学习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
Run Code Online (Sandbox Code Playgroud)
您需要保持文件名和文件句柄之间的差异.此外,代码是非惯用的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
Run Code Online (Sandbox Code Playgroud)
这是有效的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
Run Code Online (Sandbox Code Playgroud)
更好地了解库,您可能会发现以下快捷方式:
first_file_contents = File.read(from_file)
File.write(to_file, second_file_contents)
Run Code Online (Sandbox Code Playgroud)
多一点经验会给你这个:
require 'fileutils'
FileUtils.copy_file(from_file, to_file)
Run Code Online (Sandbox Code Playgroud)
编辑:感谢Stefan发现了一个缺失的论点.
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |