Menu
Coddy logo textTech

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 + 5

This 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 + 5

Now 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.1

You 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_s
challenge icon

Challenge

Easy

Read 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:

  1. The sum of both numbers
  2. 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.5

Cheat 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 + 5

Use .to_f for decimal numbers:

price = gets.chomp.to_f
puts price * 1.1

Convert numbers back to strings using .to_s:

count = 42
puts "Count: " + count.to_s

Try 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)
quiz iconTest yourself

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

All lessons in Fundamentals