0

I was trying do some sum to numbers and have a number with a very left zero and start to get wired results

142 + 3 = 145

but 0142 + 3 = 101

What is the base number data type for ruby ? ( iam using repl 2.6.3 )

lurker
  • 56,987
  • 9
  • 69
  • 103
abdoutelb
  • 1,015
  • 1
  • 15
  • 33
  • 1
    This is in the documentation: See https://docs.ruby-lang.org/en/2.0.0/syntax/literals_rdoc.html#label-Numbers – the Tin Man Apr 09 '20 at 22:45

1 Answers1

2

This is covered in Ruby's "Numbers" documentation:

You can use a special prefix 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.

Meditate on this:

0d170 # => 170
0D170 # => 170

0xaa # => 170
0xAa # => 170
0xAA # => 170
0Xaa # => 170
0XAa # => 170
0XaA # => 170

0252  # => 170
0o252 # => 170
0O252 # => 170

0b10101010 # => 170
0B10101010 # => 170

This is very common among programming languages.

If the concept of number bases is foreign, then these might help:

the Tin Man
  • 158,662
  • 42
  • 215
  • 303