Method: Bases::Number#to_base

Defined in:
lib/bases/number.rb

#to_base(new_base, opts = {}) ⇒ Array<String>|String

Return a string representation of the current number in a new_base. A string representation is always returned, even if new_base is 10. If you're using base 10 and want an integer, just call to_i on the resulting string.

Examples:

With the default separator

Number.new(3).to_base(2) #=> '11'

With a different separator

Number.new(3).to_base(2, separator: ' ~ ') #=> '1 ~ 1'

Parameters:

  • new_base (Integer|Array)

    The same as in in_base

  • opts (Hash) (defaults to: {})

    A small hash of options

Options Hash (opts):

  • :array (bool)

    If true, return the result as an array of digits; otherwise, return a string. This defaults to false.

Returns:

Raises:

  • (NoBaseSpecifiedError)

    if no source base was specified (either by passing an integer to the constructor or by using the in_base method)



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/bases/number.rb', line 89

def to_base(new_base, opts = {})
  opts[:array] = false if opts[:array].nil?

  unless defined?(@source_base)
    fail Bases::NoBaseSpecifiedError, 'No base was specified'
  end

  # Let's apply the base conversion algorithm, which returns an array of
  # digits.
  res = if native_ruby_base?(new_base)
          @value.to_s(new_base).split('')
        else
          algorithms.convert_to_base(@value, helpers.base_to_array(new_base))
        end

  opts[:array] ? res : res.join('')
end