0

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?

5
  • 3
    021 is an octal integer literal, and its value is 17, that's why when you invoke to_s on it, you get "17" - its value as a string. Commented May 30, 2019 at 2:53
  • 1
    You can use to_s(8) but you'll lose the first 0. Commented May 30, 2019 at 2:58
  • 1
    It would be helpful if you could explain what precisely is unclear to you about the documentation. That way, the Ruby developers can improve the documentation so that future developers don't fall into the same trap. Make the world a better place! Commented May 30, 2019 at 5:16
  • @JörgWMittag Possibly the problem with the documentation is that it was unread. Making it read will help. Commented May 31, 2019 at 0:05
  • @theTinMan: In that case, the question is similar: why wasn't the OP able to find the documentation and what can be improved to make the documentation easier to find? Commented May 31, 2019 at 2:21

2 Answers 2

3

Numeric literals with a leading zero are considered to be octal (base 8) numbers.

The to_s method converts the numbers to the default decimal (base 10).

  • 21 octal is 17 decimal
  • 11 octal is 9 decimal

For the expected results, remove the leading zeroes.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.