首页 > 解决方案 > 在字符串周围添加双引号会在新行上添加右引号

问题描述

我刚开始使用 Ruby 并致力于在字符串周围添加双引号。

print "Enter the name of the file to use (including the file type)"
file_name = gets.to_s
puts "\"#{file_name}\""

我得到一个输出

"test1.txt
"

非常感谢任何关于可能出错的想法。谢谢!

标签: ruby

解决方案


这与您添加的引号无关,而是您没有使用String#chomp删除包含在every gets中的尾随换行符:

gets # I type foo
# => "foo\n"

gets.chomp # I type foo
# => "foo"

你实际上并不需要to_s这里,因为它gets总是会返回一个字符串。


推荐阅读