Type Casting (Type Conversion)
Learn to convert one data type into another in Ruby.
We'll cover the following...
Casting data types example#
Let’s write a program to calculate our age in months. We’ll ask for the age in years, and our program will multiply this number by 12. Based on our knowledge from previous chapters, we should have something like this:
Note: To run the program below, we will give our
age
as input using STDIN.
Press + to interact
# Example program to convert age into monthputs "Your age?"age = gets # Get age as input from userage_months = age * 12puts "Your age is " + age_months
Enter the input below
Uh-oh! There definitely must be some mistake. It turns out that we need to multiply a string by a number (integer). Try to run this program again and type blabla
:
Press + to interact
# Example program to understand string multiplicationputs "Your age?"age = getsage_months = age * 12puts "Your age is " + age_months
Enter the input below
Explanation
The age variable is a type of string. When we multiply a string by an integer, the result is a very long string: a short string of ...