Class: Sangi::Row

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, sign:, cells:) ⇒ Row

Returns a new instance of Row.



19
20
21
22
23
24
# File 'lib/sangi/row.rb', line 19

def initialize(name:, sign:, cells:)
  @name = name
  @sign = sign
  @cells = cells
  normalize_zero_sign!
end

Instance Attribute Details

#cellsObject

Returns the value of attribute cells.



4
5
6
# File 'lib/sangi/row.rb', line 4

def cells
  @cells
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#signObject

Returns the value of attribute sign.



4
5
6
# File 'lib/sangi/row.rb', line 4

def sign
  @sign
end

Class Method Details

.from_integer(name:, value:, place_count:, rod_factory:) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/sangi/row.rb', line 6

def self.from_integer(name:, value:, place_count:, rod_factory:)
  sign = value <=> 0
  digits = SignedNumber.from_integer(value.abs).digits
  cells = place_count.times.map do |place|
    Cell.from_digit(
      place_index: place,
      digit: digits.fetch(place, 0),
      rod_factory: rod_factory
    )
  end
  new(name: name, sign: sign, cells: cells)
end

Instance Method Details

#clone_deepObject



43
44
45
46
47
48
49
# File 'lib/sangi/row.rb', line 43

def clone_deep
  Row.new(
    name: name,
    sign: sign,
    cells: cells.map(&:clone_deep)
  )
end

#magnitudeObject



26
27
28
29
30
# File 'lib/sangi/row.rb', line 26

def magnitude
  cells.each_with_index.sum do |cell, place_index|
    cell.value * (10**place_index)
  end
end

#normalize_zero_sign!Object



39
40
41
# File 'lib/sangi/row.rb', line 39

def normalize_zero_sign!
  @sign = 0 if magnitude.zero?
end

#valueObject



32
33
34
35
36
37
# File 'lib/sangi/row.rb', line 32

def value
  current_magnitude = magnitude
  return 0 if current_magnitude.zero?

  sign * current_magnitude
end