How to use "gets" and "gets.chomp" in Ruby

gets lets the user input a line and returns it as a value to your program. This value includes the trailing line break. If you then call chomp on that value, this line break is cut off. So no, what you have there is incorrect, it should rather be:

  1. gets gets a line of text, including a line break at the end.
    • This is the user input
  2. gets returns that line of text as a string value.
  3. Calling chomp on that value removes the line break

The fact that you see the line of text on the screen is only because you entered it there in the first place. gets does not magically suppress output of things you entered.


The question shouldn't be "Is this the right order?" but more "is this is the right way of approaching this?"

Consider this, which is more or less what you want to achieve:

  1. You assign a variable called tmp the return value of gets, which is a String.
  2. Then you call String's chomp method on that object and you can see that chomp removed the trailing new-line.

    Actually what chomp does, is remove the Enter character ("\n") at the end of your string. When you type h e l l o, one character at a time, and then press Enter gets takes all the letters and the Enter key's new-line character ("\n").

    1. tmp = gets
    hello
    =>"hello\n"
    
    2. tmp.chomp
    "hello"
    

gets is your user's input. Also, it's good to know that *gets means "get string" and puts means "put string". That means these methods are dealing with Strings only.


chomp is the method to remove trailing new line character i.e. '\n' from the the string. whenever "gets" is use to take i/p from user it appends new line character i.e.'\n' in the end of the string.So to remove '\n' from the string 'chomp' is used.

str = "Hello ruby\n"

str = str.chomp

puts str

o/p

"Hello ruby"


chomp returns a new String with the given record separator removed from the end of str (if present).

See the Ruby String API for more information.


  • "gets" allows user input but a new line will be added after the string (string means text or a sequence of characters)

    "gets.chomp" allows user input as well just like "gets", but there is not going to be a new line that is added after the string.

Proof that there are differences between them:

Gets.chomp

puts "Enter first text:"
text1 = gets.chomp
puts "Enter second text:"
text2 = gets.chomp
puts text1 + text2

Gets:

puts "Enter first text:"
text1 = gets
puts "Enter second text:"
text2 = gets
puts text1 + text2

Copy paste the code I gave you, run and you will see and know that they are both different.