Home » Ruby programming

chomp Method in Ruby

Ruby chomp method: Here, we are going to learn about the chomp method with its definition, syntax, and example in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 16, 2019

Ruby chomp method

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.

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.

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.

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.