Ruby Conversions
A conversion changes a value from one type into another type. Ruby conversion methods have short names like to_i and to_s.
A string becomes a number
to_i changes a string of digits into an integer. The new number can join in maths at once.
puts "42".to_i + 8A float fixes a division
Integer division drops the fraction part. Changing 7 into a float with to_f keeps the fraction part.
puts 7 / 2
puts 7.to_f / 2A number becomes a string
to_s changes a number into a string. Printing the class of the new value proves its type.
puts 42.to_s.classSame digits, two types
One string of digits can become an integer or a float. The float form prints with a decimal point.
puts "12".to_i
puts "12".to_fExample
puts "42".to_i + 8
puts 7.to_f / 2
puts 100.to_s.classKey points
- Use to_i to change a value into an integer.
- Use to_f to change a value into a float.
- Use to_s to change a value into a string.
- A string of digits can become a number with to_i.
- Changing one value in a division to a float keeps the fraction part.
In this example, the first line turns the digits 42 into a number and adds 8, printing 50. The second line changes 7 into a float and divides by 2, printing 3.5. The third line changes 100 into a string and prints its class, String.
Note
In these names, i stands for integer, f stands for float and s stands for string.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What does puts "6".to_i * 3 print?