class Numerals::Digits

Sequence of digit values, with an Array-compatible interface. Having this encapsulated here allows changing the implementation e.g. to an Integer or packed in a String, …

Attributes

digits_array[R]
radix[R]

Public Class Methods

new(*args) click to toggle source
# File lib/numerals/digits.rb, line 9
def initialize(*args)
  if Hash === args.last
    options = args.pop
  else
    options = {}
  end
  @radix = options[:base] || options[:radix] || 10
  if args.size == 1 && Array === args.first
    @digits_array = args.first
  else
    @digits_array = args
  end
  if options[:value]
    self.value = options[:value]
  end
end

Public Instance Methods

dup() click to toggle source

Deep copy

# File lib/numerals/digits.rb, line 75
def dup
  Digits[@digits_array.dup, base: @radix]
end
inspect() click to toggle source
# File lib/numerals/digits.rb, line 89
def inspect
  to_s
end
to_s() click to toggle source
# File lib/numerals/digits.rb, line 79
def to_s
  args = ""
  if @digits_array.size > 0
    args << @digits_array.to_s.unwrap('[]')
    args << ', '
  end
  args << "base: #{radix}"
  "Digits[#{args}]"
end
truncate!(n) click to toggle source
# File lib/numerals/digits.rb, line 93
def truncate!(n)
  @digits_array.slice! n..-1
end
valid?() click to toggle source
# File lib/numerals/digits.rb, line 97
def valid?
  @digits_array.none? { |x| !x.kind_of?(Integer) || x < 0 || x >= @radix }
end
value() click to toggle source

Integral coefficient

# File lib/numerals/digits.rb, line 45
def value
  if @radix == 10
    @digits_array.join.to_i
  else
    @digits_array.inject(0){|x,y| x*@radix + y}
  end
end
value=(v) click to toggle source
# File lib/numerals/digits.rb, line 53
def value=(v)
  raise "Invalid digits value" if v < 0
  if @radix < 37
    replace v.to_s(@radix).each_char.map{|c| c.to_i(@radix)}
  else
    if v == 0
      replace [0]
    else
      while v > 0
        v, r = v.divmod(@radix)
        unshift r
      end
    end
  end
end
zero?() click to toggle source
# File lib/numerals/digits.rb, line 69
def zero?
  # value == 0
  !@digits_array || @digits_array.empty? || @digits_array.all?{|d| d==0 }
end