How type casting (or type conversion) is done in Ruby
When writing code, different data types are often used for different purposes. Ruby allows the user to explicitly or implicitly typecast datatypes. Here, we will go over the following conversions:
- strings to numbers
- any other types to strings
- strings to arrays
- strings to symbols
- symbols to strings
-
Strings to numbers:
The user can convert strings to ints or floats by using the methodsto_iandto_f, respectively. -
Other types to string:
The user can convert other datatypes to string by using theto_smethod. -
Strings to arrays:
Thesplitmethod converts any string to an array. -
Strings to symbols:
Strings can be converted to symbols by using theto_symmethod. -
Symbols to strings:
Symbols can be converted to strings by using theto_smethod.
Code
The following code walks through the explanations provided above.
# converting from string to intnum1 = "5"num2 = "4"sum = num1 + num2print "Without conversion only concatenation of strings is done.\nSum = "print sumint_sum = num1.to_i + num2.to_iprint "\nWith conversion to integer arithmetic operations can be done.\nSum = "print int_sum, "\n"# converting from any datatype to stringsmyarray = ["This", "is", "a", "shot."]myarray_string = myarray.to_sprint "Array to string: ", myarray_string, "\n"#converting from strings to arrayssentence = "This is a shot."arr = sentence.splitprint "String to array: ", arr, "\n"# converting from string to symbolstring = "smiley_face"symbol = string.to_symprint "String to symbol: ", symbol
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved