Getting User Input
Part of the Fundamentals section of Coddy's Ruby journey — lesson 35 of 88.
Challenge
EasyIn 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:
- The total bill amount
- The tip percentage (as a whole number, e.g.,
15for 15%) - 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: $100To 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: 4Try 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
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 47Bill Split Calculator
Welcome MessageGetting User Input2Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False