Class: Plurimath::Formatter::Numbers::Integer

Inherits:
Object
  • Object
show all
Defined in:
lib/plurimath/formatter/numbers/integer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(symbols = {}) ⇒ Integer

Returns a new instance of Integer.



9
10
11
12
# File 'lib/plurimath/formatter/numbers/integer.rb', line 9

def initialize(symbols = {})
  @groups    = Array(symbols[:group_digits] || 3)
  @separator = symbols[:group] || ','
end

Instance Attribute Details

#formatObject (readonly)

Returns the value of attribute format.



7
8
9
# File 'lib/plurimath/formatter/numbers/integer.rb', line 7

def format
  @format
end

#groupsObject (readonly)

Returns the value of attribute groups.



7
8
9
# File 'lib/plurimath/formatter/numbers/integer.rb', line 7

def groups
  @groups
end

#separatorObject (readonly)

Returns the value of attribute separator.



7
8
9
# File 'lib/plurimath/formatter/numbers/integer.rb', line 7

def separator
  @separator
end

Instance Method Details

#apply(number, options = {}) ⇒ Object



14
15
16
# File 'lib/plurimath/formatter/numbers/integer.rb', line 14

def apply(number, options = {})
  format_groups(number)
end

#chop_group(string, size) ⇒ Object



34
35
36
# File 'lib/plurimath/formatter/numbers/integer.rb', line 34

def chop_group(string, size)
  string.slice([string.size - size, 0].max, size)
end

#format_groups(string) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/plurimath/formatter/numbers/integer.rb', line 18

def format_groups(string)
  return string if groups.empty?

  tokens = []

  tokens << chop_group(string, groups.first)
  string = string[0...-tokens.first.size]

  until string.empty?
    tokens << chop_group(string, groups.last)
    string = string[0...-tokens.last.size]
  end

  tokens.compact.reverse.join(separator)
end