Class: Dice

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

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#frequencyObject (readonly)

Returns the value of attribute frequency.



2
3
4
# File 'lib/cardtrick/dice.rb', line 2

def frequency
  @frequency
end

#totalObject (readonly)

Returns the value of attribute total.



2
3
4
# File 'lib/cardtrick/dice.rb', line 2

def total
  @total
end

Instance Method Details

#keyObject



47
48
49
# File 'lib/cardtrick/dice.rb', line 47

def key
  @h[:key] || to_dice
end

#lengthObject



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

#numObject



43
44
45
# File 'lib/cardtrick/dice.rb', line 43

def num
  @h[:num]
end

#sidesObject



39
40
41
# File 'lib/cardtrick/dice.rb', line 39

def sides
  @h[:sides]
end

#to_aObject



51
52
53
# File 'lib/cardtrick/dice.rb', line 51

def to_a
  @res
end

#to_diceObject



63
64
65
# File 'lib/cardtrick/dice.rb', line 63

def to_dice
  %[#{@h[:num]}d#{@h[:sides]}]
end

#to_iObject



55
56
57
# File 'lib/cardtrick/dice.rb', line 55

def to_i
  @total
end

#to_sObject



59
60
61
# File 'lib/cardtrick/dice.rb', line 59

def to_s
  %[I rolled #{to_dice} and got #{@total}.]
end

#valueObject



31
32
33
# File 'lib/cardtrick/dice.rb', line 31

def value
  @totals[-1]
end

#valuesObject



35
36
37
# File 'lib/cardtrick/dice.rb', line 35

def values
  @res[-1]
end