Class: Dice
- Inherits:
-
Object
- Object
- Dice
- Defined in:
- lib/cardtrick/dice.rb
Instance Attribute Summary collapse
-
#frequency ⇒ Object
readonly
Returns the value of attribute frequency.
-
#total ⇒ Object
readonly
Returns the value of attribute total.
Instance Method Summary collapse
-
#initialize(h = {}) ⇒ Dice
constructor
A new instance of Dice.
- #key ⇒ Object
- #length ⇒ Object
- #map(&b) ⇒ Object
- #next! ⇒ Object
- #num ⇒ Object
- #sides ⇒ Object
- #to_a ⇒ Object
- #to_dice ⇒ Object
- #to_i ⇒ Object
- #to_s ⇒ Object
- #value ⇒ Object
- #values ⇒ Object
Constructor Details
#initialize(h = {}) ⇒ Dice
Returns a new instance of Dice.
3 4 5 6 |
# File 'lib/cardtrick/dice.rb', line 3 def initialize h={} @h = h @res, @totals, @total, @frequency = [], [], 0, Hash.new { |h,k| h[k] = 0 } end |
Instance Attribute Details
#frequency ⇒ Object (readonly)
Returns the value of attribute frequency.
2 3 4 |
# File 'lib/cardtrick/dice.rb', line 2 def frequency @frequency end |
#total ⇒ Object (readonly)
Returns the value of attribute total.
2 3 4 |
# File 'lib/cardtrick/dice.rb', line 2 def total @total end |
Instance Method Details
#key ⇒ Object
47 48 49 |
# File 'lib/cardtrick/dice.rb', line 47 def key @h[:key] || to_dice end |
#length ⇒ Object
27 28 29 |
# File 'lib/cardtrick/dice.rb', line 27 def length @res.length end |
#map(&b) ⇒ Object
22 23 24 25 |
# File 'lib/cardtrick/dice.rb', line 22 def map &b next! b.call(self) end |
#next! ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/cardtrick/dice.rb', line 8 def next! ra, rt = [], 0 (@h[:num] || 1).times do a, x = [], rand(1..(@h[:sides] || 2)); @frequency[x] += 1; @total += x ra << x rt += x end @totals << rt @res << ra return nil end |
#num ⇒ Object
43 44 45 |
# File 'lib/cardtrick/dice.rb', line 43 def num @h[:num] end |
#sides ⇒ Object
39 40 41 |
# File 'lib/cardtrick/dice.rb', line 39 def sides @h[:sides] end |
#to_a ⇒ Object
51 52 53 |
# File 'lib/cardtrick/dice.rb', line 51 def to_a @res end |
#to_dice ⇒ Object
63 64 65 |
# File 'lib/cardtrick/dice.rb', line 63 def to_dice %[#{@h[:num]}d#{@h[:sides]}] end |
#to_i ⇒ Object
55 56 57 |
# File 'lib/cardtrick/dice.rb', line 55 def to_i @total end |
#to_s ⇒ Object
59 60 61 |
# File 'lib/cardtrick/dice.rb', line 59 def to_s %[I rolled #{to_dice} and got #{@total}.] end |
#value ⇒ Object
31 32 33 |
# File 'lib/cardtrick/dice.rb', line 31 def value @totals[-1] end |
#values ⇒ Object
35 36 37 |
# File 'lib/cardtrick/dice.rb', line 35 def values @res[-1] end |