|
What we've observed from these example is the fact that spaces will be ignored when converting from strings to integers." 555 " converted to integer will result in "555"
When converting something different than a string of numbers, the result will be 0 if you use the ".to_s" method or an error if you use the "Integer()" instead.
If you are working with binary,octal or hexadecimal strings, there are certain rules to be followed when converting.
-> a string in binary needs to start with 0b
-> a string in octal needs to start with 0
-> a string in hexadecimal needs to start with 0x
Converting from any of these will work only with the Integer method, ".to_i" will return 0.
If you want to use the ".to_i" method, you don't need to use any supplementary tag indicators (0b,0 or 0x) before your string.Instead, you will use parameters (10 for base 10, 2 for binary, 8 for octal and 16 for hexadecimal )
Remember not to include any numbers higher than the base indicator in your string or it will get ignored or result in a an error if you used the Integer method.
So if the base is 2, make sure your string contains only 0 and/or 1, if the base is 8, make sure the string does not contain 8 itself too because from 0 to 7 there are already 8 numbers and so on...
The ".to_i" method supports conversions up to base 36.
You can also convert a number straight to a certain base by doing something similar:
x=555.to_s(2)
Or use the % method included in the String class:
binary="%b" % 555
octal="%o" % 555
hexadecimal="%x" % 555
|