Class: Sangi::SignedNumber

Inherits:
Object
  • Object
show all
Defined in:
lib/sangi/signed_number.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sign:, digits:) ⇒ SignedNumber

Returns a new instance of SignedNumber.



12
13
14
15
# File 'lib/sangi/signed_number.rb', line 12

def initialize(sign:, digits:)
  @digits = digits.empty? ? [0] : digits
  @sign = @digits.all?(&:zero?) ? 0 : sign
end

Instance Attribute Details

#digitsObject (readonly)

Returns the value of attribute digits.



3
4
5
# File 'lib/sangi/signed_number.rb', line 3

def digits
  @digits
end

#signObject (readonly)

Returns the value of attribute sign.



3
4
5
# File 'lib/sangi/signed_number.rb', line 3

def sign
  @sign
end

Class Method Details

.from_integer(value) ⇒ Object



5
6
7
8
9
10
# File 'lib/sangi/signed_number.rb', line 5

def self.from_integer(value)
  sign = value <=> 0
  digits = value.abs.to_s.chars.reverse.map(&:to_i)
  digits = [0] if digits.empty?
  new(sign: sign, digits: digits)
end

Instance Method Details

#to_iObject



17
18
19
20
21
# File 'lib/sangi/signed_number.rb', line 17

def to_i
  return 0 if sign.zero?

  sign * digits.reverse.join.to_i
end