Menu
Coddy logo textTech

Getting User Input

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

challenge icon

Challenge

Easy

In the previous lesson, you created a welcome message for the Bill Split Calculator. Now, add the functionality to collect user input for the bill calculation.

After your existing welcome message, read three inputs from the user:

  1. The total bill amount
  2. The tip percentage (as a whole number, e.g., 15 for 15%)
  3. The number of people splitting the bill

Read each input using gets.chomp and convert them to numeric values using .to_f. Store them in variables named bill, tip_percent, and people.

After reading the inputs, display a confirmation message showing what was entered in the following format:

Bill: $[bill]
Tip: [tip_percent]%
People: [people]

Use puts for all output and format numbers using Ruby's % string formatting operator with the %g specifier, which removes unnecessary trailing zeros (e.g., 75.50 displays as 75.5, and 100.0 displays as 100).

The % operator works like this: "format string" % value. For example:

puts "Bill: $%g" % 75.5   # => Bill: $75.5
puts "Bill: $%g" % 100.0  # => Bill: $100

To include a literal % sign in the output (such as for the tip percentage), use %% in the format string — the double percent is how you escape a literal percent sign:

puts "Tip: %g%%" % 18.0   # => Tip: 18%

For example, if the inputs are 120, 18, and 4, the complete output should be:

Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $120
Tip: 18%
People: 4

Try it yourself

# TODO: Write your code below
# Use puts to display the welcome message
# Remember to use \n for new lines
puts "Welcome to the Bill Split Calculator!\nLet's split your bill fairly."

All lessons in Fundamentals