Is there an easy way to express arbitrary base integers in Ruby?

Erlang has a very good syntax for expressing integers with an arbitrary base. That base#number.

Example:

> 2#101010.
42
> 16#2A.
42

Is there something similar in Ruby? I already know #to_i(base=10).

+3
source share
4 answers

There's a good list of possible literals, but basically it comes down to

10 # base 10 by default
0b1010 # base 2
012 # base 8
0xa # base 16
+4
source

A simple, though not very effective or safe way to do this for arbitrary databases:

class Fixnum
  def as_base(b)
    to_s.to_i(b)
  end
end

101010.as_base(2)
42

(And you will need to do the same class Bignumfor working with arbitrarily large integer literals ...)

+5
source

, C-inspired 0x , 0b 0 . to_i .

+3

If you have an int, you can express it in any database using to_s, just like to_i in a string.

irb(main):013:0> puts 255.to_s(2)
11111111
+3
source

All Articles