DEV Community

Olimpio
Olimpio

Posted on • Updated on

TIL: How does .chomp method works?

As I'm learning Ruby on Codecademy I've come across many methods and I'm learning many things. But as I want to master this language, I'm taking some time to dive into some new things I learn every day. Today I want to go in depth on:

How does .chomp method work?

First of all, put in mind that Ruby is an Object Oriented language and everything in Ruby is an object. So, when we call the .chomp method on a value/object it removes the line break.

Actually, what .chomp does, is removing the Enter character at the end of your string. When you type d e v t o, each character at a time and then press Enter gets takes all the letters and the Enter. Remember that Enter is just another character in Ruby.

For example:

input = gets # get a string
Bem Vindo
=> "Bem Vindo\n" # when you hit the enter keyboard it adds a character
Enter fullscreen mode Exit fullscreen mode

Now let us remove that enter character

puts input.chomp
Enter fullscreen mode Exit fullscreen mode

or we can remove right away when typing it

input = gets.chomp # gets require a string as input and chomp will delete the line break that comes with that string
Enter fullscreen mode Exit fullscreen mode

gets is your User's input. Also, it's good to know that gets or puts, mean get string or put string for puts. That means these methods are dealing with strings only.

We can even use the .chomp method to remove a substring of a string in that way.

str = "Hello"

str.chomp("lo")
Enter fullscreen mode Exit fullscreen mode

Resources:

What is Ruby
Help and documentation for the Ruby programming language.
Everything is object in Ruby
Chomp method - Ruby Docs

Thanks.

Top comments (0)