What is the Difference Between Chomp and Strip in Ruby?

February 10, 2015 | Ruby


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: Ruby gets

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 to gets.chomp. Here's what happens:

Ruby using the chomp method

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 or gets.chomp, we're doing gets.strip. Here's what that gets us:

Ruby using the strip method

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.

Want to Improve Your Designs?

Get my best articles, design tips and other resources once a week.

If I don't help you improve your designs, unsubscribe at any time.

Sign Up For Free


Sign In