Class: Nuffle::Calculator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Calculator

Returns a new instance of Calculator.



15
16
17
# File 'lib/nuffle.rb', line 15

def initialize(input)
  validate(input)
end

Instance Attribute Details

#equationObject (readonly)

Returns the value of attribute equation.



10
11
12
# File 'lib/nuffle.rb', line 10

def equation
  @equation
end

#inputObject (readonly)

Returns the value of attribute input.



10
11
12
# File 'lib/nuffle.rb', line 10

def input
  @input
end

#resultObject (readonly)

Returns the value of attribute result.



10
11
12
# File 'lib/nuffle.rb', line 10

def result
  @result
end

#rollsObject (readonly)

Returns the value of attribute rolls.



10
11
12
# File 'lib/nuffle.rb', line 10

def rolls
  @rolls
end

Instance Method Details

#calculateObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/nuffle.rb', line 19

def calculate
  # reset the rolls array
  @rolls = []

  # throw rolls and replace 'xdy' dice notation with results
  @equation = @input.gsub(/(\d+)d(\d+)/) do |match|
    rolls = []

    (1..$1.to_i).each do
      rolls << 1 + rand($2.to_i)
    end

    # save individual roll results
    @rolls << {
        'notation' => match,
        'rolls' => rolls
      }

    "(#{rolls.join(" + ")})"
  end

  # cast integers to floats
  equation = @equation.gsub(/\b(\d+)\b/) do |match|
    $1.to_f.to_s
  end

  # calculate result
  @result = eval(equation);

  # cast result to integer if a whole float
  @result = @result.to_i if @result % 1 == 0

  self
end