Class: StringCalculator

Inherits:
Object
  • Object
show all
Includes:
Tokenizer
Defined in:
lib/calculator/string_calculator.rb

Instance Method Summary collapse

Methods included from Tokenizer

#ints, #is_i?, #tokens

Constructor Details

#initialize(value = 0) ⇒ StringCalculator

Returns a new instance of StringCalculator.



5
6
7
# File 'lib/calculator/string_calculator.rb', line 5

def initialize(value = 0)
  @value = value
end

Instance Method Details

#add(string) ⇒ Object



13
14
15
16
17
# File 'lib/calculator/string_calculator.rb', line 13

def add(string)
  check_negatives(string)
  @value += sum_ints(string)
  self
end

#check_negatives(string) ⇒ Object



29
30
31
32
33
# File 'lib/calculator/string_calculator.rb', line 29

def check_negatives(string)
  negs = ints(string).select { |i| i<0 }
  raise "Negatives not allowed! #{negs.join(', ')}" if negs.any?
  self
end

#subtract(string) ⇒ Object



24
25
26
27
# File 'lib/calculator/string_calculator.rb', line 24

def subtract(string)
  @value -= sum_ints(string)
  self
end

#sum_ints(string) ⇒ Object



19
20
21
# File 'lib/calculator/string_calculator.rb', line 19

def sum_ints(string)
  ints(string).inject(:+)
end

#valueObject



9
10
11
# File 'lib/calculator/string_calculator.rb', line 9

def value
  @value
end