Type Casting (Type Conversion)
Explore how to perform type casting in Ruby to convert strings into integers and vice versa. This lesson helps you understand Ruby's methods like to_i and to_s, allowing you to fix common type errors and write programs that handle input correctly.
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
ageas input using STDIN.
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:
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 ...