lib/games_dice/dice.rb in games_dice-0.3.7 vs lib/games_dice/dice.rb in games_dice-0.3.8
- old
+ new
@@ -61,34 +61,25 @@
attr_reader :result
# Simulates rolling dice
# @return [Integer] Sum of all rolled dice
def roll
- @result = @offset + @bunch_multipliers.zip(@bunches).inject(0) do |total,mb|
- m,b = mb
- total += m * b.roll
- end
+ @result = @offset + bunches_weighted_sum( :roll )
end
# @!attribute [r] min
# Minimum possible result from a call to #roll
# @return [Integer]
def min
- @min ||= @offset + @bunch_multipliers.zip(@bunches).inject(0) do |total,mb|
- m,b = mb
- total += m * b.min
- end
+ @min ||= @offset + bunches_weighted_sum( :min )
end
# @!attribute [r] max
# Maximum possible result from a call to #roll
# @return [Integer]
def max
- @max ||= @offset + @bunch_multipliers.zip(@bunches).inject(0) do |total,mb|
- m,b = mb
- total += m * b.max
- end
+ @max ||= @offset + bunches_weighted_sum( :max )
end
# @!attribute [r] minmax
# Convenience method, same as [dice.min, dice.max]
# @return [Array<Integer>]
@@ -133,12 +124,20 @@
end
private
def array_to_sum array
- sum_parts = [ array.first < 0 ? '-' + array.first.abs.to_s : array.first.to_s ]
- sum_parts += array.drop(1).map { |n| n < 0 ? '- ' + n.abs.to_s : '+ ' + n.to_s }
- sum_parts += [ '=', array.inject(:+) ]
- sum_parts.join(' ')
+ ( numbers_to_strings(array) + [ '=', array.inject(:+) ] ).join(' ')
+ end
+
+ def numbers_to_strings array
+ [ array.first.to_s ] + array.drop(1).map { |n| n < 0 ? '- ' + n.abs.to_s : '+ ' + n.to_s }
+ end
+
+ def bunches_weighted_sum summed_method
+ @bunch_multipliers.zip(@bunches).inject(0) do |total,mb|
+ m,b = mb
+ total += m * b.send( summed_method )
+ end
end
end # class Dice