使用!ruby中的chomp方法
我是ruby的新手。当我试图阅读一行没有换行符的文字时,我学习了chomp方法。此方法用于从字符串结尾删除\n。因此,我尝试了以下场景 节目:使用!ruby中的chomp方法,ruby,Ruby,我是ruby的新手。当我试图阅读一行没有换行符的文字时,我学习了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
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
但它不会删除字符串末尾的换行符。但是如果‘!’在chomp char.chomp!的末尾提供!,它工作正常。所以
“需要什么”!”为什么使用它?什么代表?作为,chomp返回一个新行被删除的字符串,而chomp!修改字符串本身
因此,char.chomp//Try to remove\n在字符串末尾返回一个新字符串,但您不能将删除新行的新字符串分配给任何变量
以下是可能的修复方法:
char.chomp! // Try to remove \n at the end of string
arr << char // Append the line into array
或
或
执行此char.chomp时,输出将没有\n个字符,但char中的字符串在ruby中保持不变!是一种约定,用于在方法之后更改对象本身,这并不意味着只是添加!对方法的修改将更改该对象,但这只是方法定义中遵循的约定,因此如果执行char.chomp!,它将改变char本身的值,这就是您看到正确结果的原因。在这里,你可以做的只是arr最终的方法!指示该方法将修改其所调用的对象。Ruby调用这些危险的方法是因为它们改变了其他人可能引用的状态
arr = Array.new;
while true
char = gets
if char == nil
break
end
char.chomp
puts char
// result = 'your string/n' (The object reference hasn't got changed.)
char2 = char.chomp
puts char2
// result = 'your string' (The variable changed but not the object reference)
char.chomp!
puts char
// result = 'your string' (The object reference chaned)
Now you can either do,
arr << char // Append the line into array
or,
arr << char2
end
p arr // print the array
它们都会给出相同的结果。在ruby中!在方法更改对象本身后使用=>这实际上是不正确的。这个只是可以在方法名称中使用的字符。而常见的惯例是使用!表示对象的破坏性或就地修改,但情况并非总是如此。只是使用而已!这并不意味着它总是修改对象。是的,这是真的,我的意思是,这是一个惯例,在大多数方法中都遵循,我已经编辑了我的响应。因此,如果我使用!在方法结束时,该操作将处理对象本身。是吗?在这种特殊情况下,是的。@mrg:不是。它和!一点关系都并没有!。Ruby不关心这些方法的调用。它们可以被称为strip_空格和strip_空格。它们恰巧被称为chomp and chomp!,但它们也可以被称为foo和bar。@Zabba我认为comp在您上一个代码示例中是一个输入错误。哇!是的,这是一个打字错误:在Ruby中用s来表示评论。投票被否决的原因是什么,你发现了什么错误?
str = char.chomp // Try to remove \n at the end of string
arr << str // Append the line into array
arr << char.chomp // Append the line into array
arr = Array.new;
while true
char = gets
if char == nil
break
end
char.chomp
puts char
// result = 'your string/n' (The object reference hasn't got changed.)
char2 = char.chomp
puts char2
// result = 'your string' (The variable changed but not the object reference)
char.chomp!
puts char
// result = 'your string' (The object reference chaned)
Now you can either do,
arr << char // Append the line into array
or,
arr << char2
end
p arr // print the array