8. Handling user input

8.3 gets goes with chomp

When we ask user for a name let’s see what user does.

User types the name and then user hits “enter” on the keyboard. That “enter” creates a new line and even that “enter” is captured by gets.

name = gets
John Smith

Now the value of name is John Smith\n. We can check this by using name.inspect.

Execute the code below and when the program asks for name then type “John Smith” and then hit enter.

In the above case we will see that after the name there is a \n.

Removing the trailing \n with chomp

We need to remove that \n and Ruby provides chomp method for that.

This time when we ask user for input we are going to use chomp to remove the \n from the

In the above case we are displaying the user input using inspect and this time we do not see trailing \n. That’s because the trailing \n was removed by using chomp.