DEV Community

Olimpio
Olimpio

Posted on • Edited on

1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay