Sometimes I have integers like these 021 or 011.
If I try to convert them to a string, the result will be:
p 021.to_s # "17" instead "021" p 011.to_s # "9" instead "011" Why does this happen and how can I convert the integers to strings?
You can refer to the literals documentation to find the special prefixs to write numbers in decimal, hexadecimal, octal or binary formats.
For decimal numbers use a prefix of 0d, for hexadecimal numbers use a prefix of 0x, for octal numbers use a prefix of 0 or 0o, for binary numbers use a prefix of 0b. The alphabetic component of the number is not case-sensitive.
21 or 0d21 is considered as number in decimal format but 021 is considered as number in octal format. And when interpreted to print it, it uses default decimal format.
021is an octal integer literal, and its value is17, that's why when you invoke to_s on it, you get"17"- its value as a string.to_s(8)but you'll lose the first 0.