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:
The user can convert strings to ints or floats by using the methods to_i
and to_f
, respectively.
Other types to string:
The user can convert other datatypes to string by using the to_s
method.
Strings to arrays:
The split
method converts any string to an array.
Strings to symbols:
Strings can be converted to symbols by using the to_sym
method.
Symbols to strings:
Symbols can be converted to strings by using the to_s
method.
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