TIL: How does .chomp method works?- 1 min
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:
.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.
.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.
input = gets # get a string Bem Vindo => "Bem Vindo\n" # when you hit the enter keyboard it adds a character
Now let us remove that enter character
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
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")