我是红宝石的新手.当我尝试读取没有换行符的行时,我学习了chomp方法.此方法用于从字符串末尾删除\n.所以,我尝试了以下方案.
程序:
arr = Array.new;
while true
char = gets // Read line from input
if char == nil // If EOF reach then break
break
end
char.chomp // Try to remove \n at the end of string
arr << char // Append the line into array
end
p arr // print the array
Run Code Online (Sandbox Code Playgroud)
输出:
$ ruby Array.rb
abc
def
["abc\n", "def\n"]
$
Run Code Online (Sandbox Code Playgroud)
但它不会删除字符串末尾的换行符.但如果'!' 在chomp(char.chomp!)的末尾提供,它工作正常.那么"!"的需求是什么?以及为什么使用它?什么 !代表 ?
正如良好的文档所说,chomp返回一个新的字符串,删除了换行符,而chomp!修改字符串本身.
因此,char.chomp // Try to remove \n at the end of string返回一个新字符串,但是您没有将新行删除的新字符串分配给任何变量.
以下是可能的修复:
char.chomp! // Try to remove \n at the end of string
arr << char // Append the line into array
Run Code Online (Sandbox Code Playgroud)
要么
str = char.chomp // Try to remove \n at the end of string
arr << str // Append the line into array
Run Code Online (Sandbox Code Playgroud)
要么
arr << char.chomp // Append the line into array
Run Code Online (Sandbox Code Playgroud)