Class: Nuffle::Calculator
- Inherits:
-
Object
- Object
- Nuffle::Calculator
- Defined in:
- lib/nuffle.rb
Instance Attribute Summary collapse
-
#equation ⇒ Object
readonly
Returns the value of attribute equation.
-
#input ⇒ Object
readonly
Returns the value of attribute input.
-
#result ⇒ Object
readonly
Returns the value of attribute result.
-
#rolls ⇒ Object
readonly
Returns the value of attribute rolls.
Instance Method Summary collapse
- #calculate ⇒ Object
-
#initialize(input) ⇒ Calculator
constructor
A new instance of Calculator.
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
#equation ⇒ Object (readonly)
Returns the value of attribute equation.
10 11 12 |
# File 'lib/nuffle.rb', line 10 def equation @equation end |
#input ⇒ Object (readonly)
Returns the value of attribute input.
10 11 12 |
# File 'lib/nuffle.rb', line 10 def input @input end |
#result ⇒ Object (readonly)
Returns the value of attribute result.
10 11 12 |
# File 'lib/nuffle.rb', line 10 def result @result end |
#rolls ⇒ Object (readonly)
Returns the value of attribute rolls.
10 11 12 |
# File 'lib/nuffle.rb', line 10 def rolls @rolls end |
Instance Method Details
#calculate ⇒ Object
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 |