Home »
Ruby Tutorial
chomp Method in Ruby
By IncludeHelp Last updated : December 01, 2024
Description and Usage
chomp is a predefined method in Ruby's library which is used to eliminate implicit newline character '\n' attached with the string entered by the user during run time. We use gets method in Ruby for taking input from the user but it provides a new line with the string. chomp provides help to remove it because newline is not desired in the string most of the times as newline creates problems when some time of processing takes place in the string.
Use of chomp
For a better understating of chomp, let us understand what happens in the absence of chomp? Read the following code when the chomp is not used and analyze the output.
Example
puts "Enter your name"
str=gets
puts "Hi "+str+"Welcome to Includehelp."
This might be the most basic program one can write in Ruby. Here we are using gets without chomp method. On the console, when the user will be asked for entering his name, the string will implicitly get a newline character. This will result in the following output,
Enter your name
Hitakshi
Hi Hitakshi
Welcome to Includehelp.
Handling Newline Issues with the chomp Method
So, you can observe in the above output that with the presence of newline, when the string is required to be printed, it creates a gap between whole string by adjusting rest of the string in a new line. No doubt, there is nothing negative in displaying the rest of the characters in a new line but sometimes when the whole string is supposed to be displayed in a single line, it creates a problem.
Here, chomp needs to be employed. Let us make changes in the same code by attaching chomp method with the gets method. Observe the code and output after modification.
Example
puts "Enter your name"
str=gets.chomp
puts "Hi "+str+" Welcome to Includehelp."
The output after modification is as follows,
Enter your name
Hitakshi
Hi Hitakshi Welcome to Includehelp.
You can observe that the above string is getting printed in the same line because now we have made the use of chomp method which is not letting \n to be attached with the string. It is utilized for chopping newline character which is attached at the end of the string.
There is one more method defined in Ruby's method which works like chomp which is called chop but with a basic difference that chomp removes \n from the string whereas ‘chop’ removes any last character from the string.