When getting user input you may want to remove whitespace. Let me show you how to do this.
First, let's not remove any whitespace.
puts "What is your name?" name = gets puts "Hi " + name + ". Nice to meet you."
This little code results in this:
Notice I added some spaces before I typed my name. Also, I pushed enter to submit my name and that was included as part of my name. But, I don't want that return or the space before my name.
So, let's use the chomp method.
puts "What is your name?" name = gets.chomp puts "Hi " + name + ". Nice to meet you."
The only thing I changed was the second line from
gets.chomp. Here's what happens:
We are getting closer, the whitespace after my name was cleared up but what about the whitespace before AND after my name? Enter the strip method:
puts "What is your name?" name = gets.strip puts "Hi " + name + ". Nice to meet you."
Again, everything is the same except the second line and instead of
gets.chomp, we're doing
gets.strip. Here's what that gets us:
Now we have just what we want - whitespace removed before and after user input.
So, to summarize,
gets doesn't remove any white space. The
chomp method removes whitespace AFTER the user input. And the
strip method removes whitespace BEFORE and AFTER the user input.