Ruby 文件输出问题
Ruby file output issue
我已经写了一些 ruby 来自动创建批处理文件,问题在于 GUI 中的结果输出;
文件已输出,但格式确实看起来很奇怪。此外,文件名都以“.txt”结尾,但 MacOS 不这样看。即您无法在 Textedit 中点击打开。
代码如下;
puts "Please enter amount of files to create: "
file_count = gets.to_i
puts "Thanks! Enter a filename header: "
file_head = gets
puts "And a suffix?"
suffix = gets
puts "Please input your target directory:"
Dir.chdir(gets.chomp)
while file_count != 0
filename = "#{file_head}_#{file_count}#{suffix}"
File.open(filename, "w") {|x| x.write("This is #{filename}.")}
file_count -= 1
end
随时欢迎有关缩短长度或重构的提示。
Kernel#gets
文档包含:
The separator is included with the contents of each record.
默认情况下,分隔符是换行符(参见 $/
)。所以 file_head
和 suffix
都以换行符结尾。 filename
当然也是。因此,您的文件的扩展名不是 .txt
,因为它实际上是 ".txt\n"
(在 Ruby 字符串表示法中)。应用程序从字面上获取换行符并继续在新行上写入文件名。这就是它看起来如此奇怪的原因!
您已经知道修复它的方法:调用 String#chomp
以删除结尾的换行符(分隔符)。请参阅代码中包含 Dir.chdir
的行作为示例。
我已经写了一些 ruby 来自动创建批处理文件,问题在于 GUI 中的结果输出;
文件已输出,但格式确实看起来很奇怪。此外,文件名都以“.txt”结尾,但 MacOS 不这样看。即您无法在 Textedit 中点击打开。
代码如下;
puts "Please enter amount of files to create: "
file_count = gets.to_i
puts "Thanks! Enter a filename header: "
file_head = gets
puts "And a suffix?"
suffix = gets
puts "Please input your target directory:"
Dir.chdir(gets.chomp)
while file_count != 0
filename = "#{file_head}_#{file_count}#{suffix}"
File.open(filename, "w") {|x| x.write("This is #{filename}.")}
file_count -= 1
end
随时欢迎有关缩短长度或重构的提示。
Kernel#gets
文档包含:
The separator is included with the contents of each record.
默认情况下,分隔符是换行符(参见 $/
)。所以 file_head
和 suffix
都以换行符结尾。 filename
当然也是。因此,您的文件的扩展名不是 .txt
,因为它实际上是 ".txt\n"
(在 Ruby 字符串表示法中)。应用程序从字面上获取换行符并继续在新行上写入文件名。这就是它看起来如此奇怪的原因!
您已经知道修复它的方法:调用 String#chomp
以删除结尾的换行符(分隔符)。请参阅代码中包含 Dir.chdir
的行作为示例。