mrg mrg - 5 months ago 14
Ruby Question

Use of ! and chomp method in ruby

I am a newbie to ruby. While I try to read a line without newline character I learn about chomp method. This method is used to remove \n from the end of the string. So, I tried the following scenario.

Program:

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


Output:

$ ruby Array.rb
abc
def
["abc\n", "def\n"]
$


But it doesn't remove newline at the end of the string. But if '!' is provided at the end of chomp (char.chomp!), it worked properly. So
what is the need of '!' and why it is used ? what ! stands for ?

Answer

As the good documentation says, chomp returns a new string with newline removed, while chomp! modifies the string itself.

So, char.chomp // Try to remove \n at the end of string returns a new string, but you are not assigning that new string with newline removed to any variable.

Here are possible fixes:

char.chomp!      // Try to remove \n at the end of string
arr << char     // Append the line into array

or

str = char.chomp      // Try to remove \n at the end of string
arr << str     // Append the line into array

or

arr << char.comp     // Append the line into array
Comments