Menu
Coddy logo textTech

Chomp Method

Part of the Fundamentals section of Coddy's Ruby journey — lesson 30 of 88.

In the previous lesson, you saw that gets includes the newline character when the user presses Enter. The chomp method removes this trailing newline from a string.

name = gets.chomp
puts "Hello, #{name}!"

If the user types "Alice", the output is now clean:

Hello, Alice!

Without chomp, there would be an unwanted blank line before the exclamation mark. You can chain chomp directly onto gets as shown above, which is the most common pattern you'll see in Ruby programs.

Let's verify the difference using p:

with_newline = gets
without_newline = gets.chomp

p with_newline      # "Ruby\n"
p without_newline   # "Ruby"

The chomp method only removes the newline at the end. It doesn't affect any other characters in the string. From now on, you'll typically want to use gets.chomp whenever you read user input.

challenge icon

Challenge

Easy

Read a city name from the user using gets.chomp and store it in a variable called city.

Then use string interpolation with puts to output a welcome message in the following format:

Welcome to [city]!

For example, if the input is Tokyo, the output should be:

Welcome to Tokyo!

The exclamation mark should appear directly after the city name with no extra spaces or blank lines.

Cheat sheet

The chomp method removes the trailing newline character from a string. This is essential when reading user input with gets, which includes the newline when the user presses Enter.

Chain chomp directly onto gets:

name = gets.chomp
puts "Hello, #{name}!"

Comparing with and without chomp:

with_newline = gets        # "Ruby\n"
without_newline = gets.chomp   # "Ruby"

The chomp method only removes the newline at the end and doesn't affect other characters in the string.

Try it yourself

# Read the city name from the user
city = gets.chomp

# TODO: Write your code below to output the welcome message using string interpolation
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals