|
As wikipedia says,"typecasting is the conversion of a variable's data type to another data type to bypass some restrictions imposed on datatypes"
You've already recently learned how to convert symbols to strings or integers using ".to_s" and ".to_i"
A character can also be converted to an integer by using the ".to_s" method.
To convert something to a hash you would use the ".to_h" method and to convert something to an array you would use the ".to_a" method.
How to convert strings to numbers
This is a weird one,right? How can you convert strings into numbers? well, it's possible as long the string contains numbers, otherwise you will get an error.If the string contains first numbers and then letters, only the numbers will be converted to an integer and then type conversion will stop.
Let's approach this subject by using lots of examples of real code:
x="555".to_i
x=Integer("555")
x="555string"
x=Integer("555string")
x="3.14".to_f
x=Float("3.14")
x="string".to_i
x=Integer("string")
x=" 555 "
Now let's see and explain the results of the above:
|