Type Conversion
Part of the Fundamentals section of Coddy's Ruby journey — lesson 31 of 88.
When you read input with gets, Ruby always returns a string, even if the user types a number. This becomes a problem when you need to perform calculations.
age = gets.chomp
puts age + 5This code will cause an error because you can't add a number to a string. To fix this, you need to convert the string to a number using .to_i (to integer) or .to_f (to float):
age = gets.chomp.to_i
puts age + 5Now if the user types "20", the output will be 25. Use .to_f when you need decimal numbers:
price = gets.chomp.to_f
puts price * 1.1You can also convert numbers back to strings using .to_s. This is useful when you need to combine numbers with text without using string interpolation:
count = 42
puts "Count: " + count.to_sChallenge
EasyRead two numbers from the user as input. The first input is a whole number (integer) and the second input is a decimal number (float).
Calculate and print the following on separate lines:
- The sum of both numbers
- The product of both numbers (multiplication)
Make sure to convert each input to the appropriate numeric type before performing the calculations.
For example, if the inputs are 5 and 2.5, the output should be:
7.5
12.5Cheat sheet
When reading input with gets, Ruby always returns a string. To perform calculations, convert strings to numbers using .to_i (to integer) or .to_f (to float):
age = gets.chomp.to_i
puts age + 5Use .to_f for decimal numbers:
price = gets.chomp.to_f
puts price * 1.1Convert numbers back to strings using .to_s:
count = 42
puts "Count: " + count.to_sTry it yourself
# Read input
integer_num = gets.chomp.to_i
float_num = gets.chomp.to_f
# TODO: Write your code below to calculate the sum and product
# Output the results (print sum and product on separate lines)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables 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